Ola estou começando agora a mexer com HTML e CSS

Question: Ola estou começando agora a mexer com HTML e CSS, mas estou tento um problema pq o meu menu esta se deslocando quando dou ctrl+scrol do mouse, poderia me ajudar???
<!DOCTYPE html>

         <meta http-equiv="content-type" content="tenxt/html;  charset UTF8" />
         <meta http-equiv="X-UA-compatible" content="IE,chrome=1" />
         <meta name name="handheldFriendly" content="true" />
         <meta name="apple-touch-fullscream" content="yes" />
         <meta name="mobileotimized" content="320" />
         <meta name="viweport" content="width, intial-sacle=1" />
         <meta charset="UTF8" />

                 <title>WolfEngineering</title>
                 <link rel="Stylesheet" type="text/css" href="_css\Estilo.css" />

WolfEngineering

 Menu

 Profissinais

 Onde Ficamos

 Contato<l/i>

Empresa focada em trazer o melhor da Engenharia civil e projetos futuristas e diferenciados
                para a sua casa e para sua empresa

Progetos feitos

body{
  margin: 0

}

h1{
        text-align: center;
        font-family: verdana;
        position: absolute fixed;
         left: 38%;

}
#Topo{
        height: 350px;
        background: url('../Imagem/topo jpg.jpg')
        no-repeat center;

 }

a{
        font-size: 20px;
        color: white;
        text-decoration: none;
        margin: 0 auto;

}

p{
      text-align: center;
}

#menu{
        background: black;
        margin: 0 auto;

}

#menu ul{
      margin: 0 auto;
      width: 550px;
      position: absolute static;

}

#menu ul li{
  display: inline;
  margin: 0px 15px auto;
  position: absolute static;
}

h2{
  position: relative;
  margin: center;
}

.containerB{
    width: 1390px;
    position: absolute center;
    margin: auto;
}

.container{
    width: 1000px;
    position: relative;
    margin: 0px auto;
}
<!DOCTYPE html>

         <meta http-equiv="content-type" content="tenxt/html;  charset UTF8" />
         <meta http-equiv="X-UA-compatible" content="IE,chrome=1" />
         <meta name name="handheldFriendly" content="true" />
         <meta name="apple-touch-fullscream" content="yes" />
         <meta name="mobileotimized" content="320" />
         <meta name="viweport" content="width, intial-sacle=1" />
         <meta charset="UTF8" />

                 <title>WolfEngineering</title>
                 <link rel="Stylesheet" type="text/css" href="_css\Estilo.css" />

WolfEngineering

 Menu

 Profissinais

 Onde Ficamos

 Contato<l/i>

Empresa focada em trazer o melhor da Engenharia civil e projetos futuristas e diferenciados
                para a sua casa e para sua empresa

Progetos feitos

Comment: Detalhe q aqui no meu computador esta tudo centralizado, mas na Execução feita n esta centralizado
Answer: Isso acontece porque a div .containerB possui um valor fixo (1390px). O menu estará sempre centralizado mesmo que você faça zoom na tela.
Para resolver isso, altere a classe .containerB usando max-width e width desta forma:
.containerB{
   width: 100%;
   max-width: 1390px;
   position: absolute center;
   margin: auto;
}

body{
  margin: 0

}

h1{
        text-align: center;
        font-family: verdana;
        position: absolute fixed;
         left: 38%;

}
#Topo{
        height: 350px;
        background: url('../Imagem/topo jpg.jpg')
        no-repeat center;

 }

a{
        font-size: 20px;
        color: white;
        text-decoration: none;
        margin: 0 auto;

}

p{
      text-align: center;
}

#menu{
        background: black;
        margin: 0 auto;

}

#menu ul{
      margin: 0 auto;
      width: 550px;
      position: absolute static;

}

#menu ul li{
  display: inline;
  margin: 0px 15px auto;
  position: absolute static;
}

h2{
  position: relative;
  margin: center;
}

.containerB{
   width: 100%;
   max-width: 1390px;
   position: absolute center;
   margin: auto;
}

.container{
    width: 1000px;
    position: relative;
    margin: 0px auto;
}
<!DOCTYPE html>

         <meta http-equiv="content-type" content="tenxt/html;  charset UTF8" />
         <meta http-equiv="X-UA-compatible" content="IE,chrome=1" />
         <meta name name="handheldFriendly" content="true" />
         <meta name="apple-touch-fullscream" content="yes" />
         <meta name="mobileotimized" content="320" />
         <meta name="viweport" content="width, intial-sacle=1" />
         <meta charset="UTF8" />

                 <title>WolfEngineering</title>
                 <link rel="Stylesheet" type="text/css" href="_css\Estilo.css" />

WolfEngineering

 Menu

 Profissinais

 Onde Ficamos

 Contato<l/i>

Empresa focada em trazer o melhor da Engenharia civil e projetos futuristas e diferenciados
                para a sua casa e para sua empresa

Progetos feitos

Outros problemas no seu CSS é a utilização do position: você não
  pode definir dois valores, assim:
position: absolute static;

Você deve setar apenas 1 valor (saiba mais sobre position neste
  link).


Identifying intervals in a time series

Question: I know, I know, this must have been covered many times before, but my belief is that I don't need the usual robust solution...
Here is a time series:

I would like to automatically detect the intervals which are clearly obvious to the human eye. I highlighted the first one.
The output should be a list of the form [x1, x2], [x3, x4], ...identifying the start and end of each interval on the x axis.
The trick is probably making the tolerance at the edges of each interval a parameter of the solution.
Also how to deal with the 1:15 to 1:23 period, so that it doesn't get identified as an interval, granted it is unlike the other ones.
A trivial approach was to detect when the data crosses the median value, but that is too trivial in less obvious cases.
OK, so, maybe the approach needs to be as robust as necessary, but as simple as possible. ;)
Data for the sample time series:
https://www.dropbox.com/s/4mqe5afffsx0vr5/series.csv?dl=0
Comment: please post your data .
Comment: I added the data to the initial post.
Comment: I am curious what an "interval" is.  For instance, I see no basis to reject a solution that identifies the apparent inverted peaks--even though that would be quite different from the solution you are suggesting.  Could you provide a more specific description of the patterns you are attempting to identify?
Comment: @whuber Humm, let's see...the data is not random in nature. In this instance, the test called for 6 bursts to be produced. Yet, I would not want the number of intervals to be a parameter. I guess you could say each interval is a period of increased activity preceded and followed by a period of lower activity. Argh, that's a pretty vague description.
Answer: Given the details provided in the comments, I assume that the author aims to identify the bursts in the time-series, which are described as intervals. Detecting when the data crosses the median value would give a uniform solution, since for example in time-series with very high variance (e.g. an EPG) it would result in far too many intervals.
A very simple, linear, bursty intervals detection algorithm is described here by Ruzzo and Tompa, dealing with the problem as a Maximal Scoring Subsequences problem. Granularity can be tuned by re-applying the algorithm on the extracted intervals, until the desired granularity is reached.

Identifying intervals in a time series


White screen while running OpenGL program

Question: There are no error in this program but it is displaying a blank white screen on CodeBlocks IDE 17.12:
<code>#include <stdio.h>
#include <math.h>
#include<GL/gl.h>
#include <GL/glut.h>
#include <windows.h>

#include<GL/glext.h>
#include<GL/glu.h>
#include<stdlib.h>
#define pi 3.142
static GLfloat angle = 0;

static int submenu;
static int mainmenu;
static int value = -1;

void init()
{
    gluOrtho2D(-1000, 1000, -1000, 1000);
}
void circle(float rad)
{
    glBegin(GL_POINTS);
    glColor3f(2, 0, 0);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(rad * cos(i), rad * sin(i));
    }
    glEnd();
}
void drawString(float x, float y, float z, char *string)
{
    glColor3f(1, 1, 1);
    glRasterPos3f(x, y, z);

    for (char *c = string; *c != '\0'; c++)
    {
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *c);
    }
}

void drawhead(float x, float y, float z, char *string)
{
    glColor3f(1, 1, 1);
    glRasterPos3f(x, y, z);

    for (char *c = string; *c != '\0'; c++)
    {
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
    }
}
void drawsubhead(float x, float y, float z, char *string)
{
    glColor3f(1, 1, 1);
    glRasterPos3f(x, y, z);

    for (char *c = string; *c != '\0'; c++)
    {
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c);
    }
}
void nuc(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(0, 0, 1);
    for (float i = 0; i < (2 * pi); i = i + 0.00001)
    {
        glVertex2f(rad * cos(i), rad * sin(i));
    }
    glEnd();
}
void eleright(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(rad + 20 * cos(i), 20 * sin(i));
    }
    glEnd();
}
void eleleft(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(-(rad + 20 * cos(i)), 20 * sin(i));
    }
    glEnd();
}
void eletop(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(20 * cos(i), rad + 20 * sin(i));
    }
    glEnd();
}
void eledown(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(20 * cos(i), -(rad + 20 * sin(i)));
    }
    glEnd();
}
void eletr(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(((rad - 175) + 20 * cos(i)), ((rad - 175) + 20 * sin(i)));
    }
    glEnd();
}
void eletl(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(-((rad - 175) + 20 * cos(i)), ((rad - 175) + 20 * sin(i)));
    }
    glEnd();
}
void eledl(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(-((rad - 175) + 20 * cos(i)), -((rad - 175) + 20 * sin(i)));
    }
    glEnd();
}
void eledr(float rad)
{
    glBegin(GL_POLYGON);
    glColor3f(1, 1, 1);
    for (float i = 0; i < (2 * pi); i += 0.00001)
    {
        glVertex2i(((rad - 175) + 20 * cos(i)), -((rad - 175) + 20 * sin(i)));
    }
    glEnd();
}
void display()
{
    glClearColor(0, 0, 0.1, 0.9);

    if (value == -1)
    {
        char cn[] = "GOVERNMENT ENGINEERING COLLEGE RAMANAGAR";
        drawhead(-620, 900, 0, cn);
        char pn[] = "B.M.ROAD,RAMANAGARA-562159";
        drawsubhead(-300, 850, 0, pn);

        char dn[] = "DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING";
        drawhead(-650, 650, 0, dn);

        char prn[] = "A Mini Project On";
        drawsubhead(-150, 450, 0, prn);
        char pro[] = "ATOM SIMULATION";
        drawhead(-250, 350, 0, pro);

        char pb[] = "PROJECT BY: ";
        drawhead(-690, -150, 0, pb);

        char p1[] = "ADARSH.N";
        drawhead(-690, -250, 0, p1);
        char p1u[] = "1GG18CS002";
        drawsubhead(-690, -300, 0, p1u);

        char p2[] = "NITHIN KUMAR B";
        drawhead(-690, -400, 0, p2);
        char p2u[] = "1GG18CS028";
        drawsubhead(-690, -450, 0, p2u);

        char gb[] = "GUIDED BY: ";
        drawhead(290, -150, 0, gb);

        char g1[] = "Dr.SRI RAMACHANDRA L";
        drawhead(290, -250, 0, g1);
        char d1[] = "Professor, Dept. Of CSE, GECR";
        drawsubhead(290, -300, 0, d1);

        //char g2[] = "Sunil G L";
        //drawhead(290, -400, 0, g2);
        //char d2[] = "Assistant Professor, Dept. of CSE, SVIT";
        //drawsubhead(290, -450, 0, d2);

        char in[] = "Press enter to Continue";
        drawhead(-250, -700, 0, in);

        glutSwapBuffers();
        glutDetachMenu(GLUT_RIGHT_BUTTON);
    }
    if (value != -1)
    {
        nuc(250);
        char n[] = "NUCLEUS";
        drawString(-80, 20, 0, n);
        char d[] = "(NEUTRON + PROTON)";
        drawString(-155, -30, 0, d);
        if (value == 0)
        {
            char nu[] = "SELECT THE ELEMENT USING MENU";
            drawhead(-490, 900, 0, nu);
        }
    }
    if (value == 1)
    {
        char n[] = "HYDROGEN";
        drawhead(-100, 900, 0, n);
        circle(400);
        char o[] = "ORBIT";
        drawString(410, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        char e[] = "ELECTRON";
        drawString(420, 0, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 2)
    {
        char n[] = "HELIUM";
        drawhead(-100, 900, 0, n);
        circle(400);
        char o[] = "ORBIT";
        drawString(410, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        char e[] = "ELECTRON";
        drawString(420, 0, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 3)
    {
        char n[] = "LITHIUM";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 4)
    {
        char n[] = "BERYLLIUM";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        eledown(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 5)
    {
        char n[] = "BORON";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        eledown(600);
        eletr(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 6)
    {
        char n[] = "CARBON";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        eledown(600);
        eletr(600);
        eledl(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 7)
    {
        char n[] = "NITROGEN";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        eledown(600);
        eletr(600);
        eledl(600);
        eletl(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 8)
    {
        char n[] = "OXYGEN";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        eledown(600);
        eletr(600);
        eledl(600);
        eletl(600);
        eledr(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 9)
    {
        char n[] = "FLUORINE";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        eledown(600);
        eletr(600);
        eledl(600);
        eletl(600);
        eledr(600);
        eleleft(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }
    if (value == 10)
    {
        char n[] = "NEON";
        drawhead(-100, 900, 0, n);
        circle(400);
        circle(600);
        char o[] = "ORBIT";
        drawString(610, 0, 0, o);
        glPushMatrix();
        glRotatef(angle, 0, 0, 1);
        eleright(400);
        eleleft(400);
        eletop(600);
        eledown(600);
        eletr(600);
        eledl(600);
        eletl(600);
        eledr(600);
        eleleft(600);
        eleright(600);
        char e[] = "ELECTRON";
        drawString(0, 620, 0, e);
        glPopMatrix();
        glutSwapBuffers();
    }

    glutSwapBuffers();
}
void rotate()
{
    angle = angle + 1.0;
    if (angle > 360)
    {
        angle = angle - 360;
    }
    glClear(GL_COLOR_BUFFER_BIT);
    glutPostRedisplay();
}
void mouseControl(int button, int state, int x, int y)
{
    switch (button)
    {
    case GLUT_LEFT_BUTTON:
        if (state == GLUT_DOWN)
            glutIdleFunc(rotate);
        break;
    default:
        break;
    }
}
void keyboard(unsigned char key, int x, int y)
{
    if (key == 13)
    {
        value = 0;
        glClear(GL_COLOR_BUFFER_BIT);
        glutAttachMenu(GLUT_RIGHT_BUTTON);
        glutPostRedisplay();
    }
    else if (key == 's')
    {
        glutIdleFunc(NULL);
    }
    else if (key == 32)
    {
        glutIdleFunc(rotate);
    }
    else if (key == 'q' || key == 'Q')
    {
        exit(0);
    }
    else if (key == 27)
    {
        glutReshapeWindow(700, 700);
    }
}
void fkey(int key, int x, int y)
{

    if (key == GLUT_KEY_F10)
    {
        glutReshapeWindow(glutGet(GLUT_SCREEN_WIDTH), glutGet(GLUT_SCREEN_HEIGHT));
    }
}
void menu(int option)
{
    if (option == 13)
    {
        exit(0);
    }
    else if (option == 11)
    {
        glutIdleFunc(rotate);
    }
    else if (option == 12)
    {
        glutIdleFunc(NULL);
    }
    else if(option==14){
        value=-1;
    }
    else
    {
        value = option;
    }
    glClear(GL_COLOR_BUFFER_BIT);

    glutPostRedisplay();
}
void createMenu(void)
{
    submenu = glutCreateMenu(menu);
    glutAddMenuEntry("HYDROGEN", 1);
    glutAddMenuEntry("HELIUM", 2);
    glutAddMenuEntry("LITHIUM", 3);
    glutAddMenuEntry("BERILIUM", 4);
    glutAddMenuEntry("BORON", 5);
    glutAddMenuEntry("CARBON", 6);
    glutAddMenuEntry("NITROGEN", 7);
    glutAddMenuEntry("OXYGEN", 8);
    glutAddMenuEntry("FLUORINE", 9);
    glutAddMenuEntry("NEON", 10);
    mainmenu = glutCreateMenu(menu);
    glutAddSubMenu("SELECT THE ELEMENT", submenu);
    glutAddMenuEntry("START SIMULATION", 11);
    glutAddMenuEntry("STOP SIMULATION", 12);
    glutAddMenuEntry("GOTO HOME SCREEN",14);
    glutAddMenuEntry("EXIT", 13);

    glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(700, 700);
    glutCreateWindow("ATOM SIMULATION");
    init();
    glutDisplayFunc(display);
    glutMouseFunc(mouseControl);
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(fkey);
    createMenu();
    glutMainLoop();
    return 0;
}
</code>
How can i display the output?  What should be corrected?
Answer: You never actually do clear the framebuffer. You only set the clear color, but that's just like dipping a brush into a bucket of paint, without going to paint the wall.
Change your display function like this:
<code>void display()
{
    glClearColor(0, 0, 0.1, 0.9);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    ...
</code>


PDO exception error [database].semaphore doesnot exist

Question: I created a website in drupal 7, tested it in my localhost and works good. Now, I want to host the site in our Main server. So, I uploaded the site directory to the server and created a corresponding database for that. Updated the settings.php file with the database name, user and password.
I do hope that the site install process is done. The site is deployed within the server, database created. When I give the address of the site, it shows some PDO exception error.
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table '[database].semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 167 of /home/cpath/D-6.12/apache2/htdocs/[htdocs]/includes/lock.inc).

I tried re-installing the drupal site, it didn't work.
I even reviewed and tried all the solutions shown in drupal.org, but no way I couldn't resolve the issue.
I appreciate your valuable suggestions.
Comment: try running `update.php` [your-site]/update.php
Comment: update.php didn't work, same PDO exception error. But now the error was updated, [database].system does not exist 'code' in drupal_get_installed_schema_version() (line 155 of /home/cpath/D-6.12/apache2/htdocs/sehs/includes/install.inc). 'code'
Comment: try creating `semaphore table` on your database
**CREATE TABLE semaphore ( `name` VARCHAR(255) NOT NULL DEFAULT '', `value` VARCHAR(255) NOT NULL DEFAULT '', `expire` DOUBLE NOT NULL, PRIMARY KEY (name), INDEX expire (expire) )**
Comment: What database server?  How did you take the backup?  How did you do the restore?  Are you positive that the semaphore table is in the backup?
Comment: When you copy MySQL databases that are innoDB you need to copy the ib* files. Found explanation here: http://stackoverflow.com/questions/4260546/mysql-table-does-not-exist-error-but-it-does-exist
Comment: This question is duplicate. I already answered this in [here](https://drupal.stackexchange.com/questions/114656/drupal-pdoexception-when-creating-the-table/114671#114671). this is because of your database engine which must be converted to `MyISAM` from `InnoDB`. go to that link for more detail.
Comment: I have gone through this post, but didn't dare to try it. Are you sure it works???
Comment: yes be sure. 98% of my website was completed and suddenly the same error reported. it took about one week to find the solution. just take a look at the comment below my answer. it worked for that guy too
Comment: hey, it didn't work man. I converted the database engine with MyISAM as you said. And even reflected the same changes in other databases within the directory. Other sites works fine, my site show the same error. NO CHANGE IN THE EXCEPTION.
Comment: did you change the drupal core? check your database to see if the `sepmaphore` is there. again export your DB to make sure that the engine is MyISAM
Comment: The error message is the same, but the scenario is different enough to not make this a dup.  This question is about a dev-to-live deployment, while the linked one is about a 6-to-7 upgrade.
Comment: @Drupalist :: drupal core?? why do we need to change the drupal core. I just changed the scheme.inc file in includes/databases/mysql/scheme.inc.. And the database : I created a new database after uploading the drupal site directory (within the server) and it is empty.
Comment: @GIRI by Drupal core I meant the `schema.inc`. why your DB is empty?! like I said export the old DB as `.sql` , open it in notepad or any text editor, look for `InnoDB` and replace it with `MyISAM` , save it. in the server `phpmyadmin` delete all the tables of the DB and import the new `.sql` file
Comment: @GIRI you welcome
Comment: can I know why InnoDB is not working?? heard it was a upgrade to MyISAM, then what was issue with it??
Comment: I don't know, but maybe it is because of some configuration in the server! it shouldn't be true because my website was working and it suddenly reported the error. anyway thanks to MyISAM
Comment: I suspect this solution is painting over a larger problem with the server.  My guess is that there is a configuration problem, or something is timing out w/ a silent error message.  Editing core files like this is never a good long term plan.  To be honest, I don't know how well tested Drupal 7 is anymore with MyISAM, so you may have problems under load, and other places where  proper transactions come into play.
Comment: @MPD Maybe you don't believe it but I saw the same error in Wordpress CMS and I solved it in the same way. Drupal 7 is totally compatible with MyISAM but I hope such thing doesn't occur in Drupal 8.
Comment: @Drupalist I have no doubt that this provided a solution for you.  The [Drupal 7 database requirements](https://drupal.org/requirements/database) do list MyISAM.  However, MyISAM does not support transactions, and the driver will silently skip any transaction requests.  This may cause problems under load, where transactions are needed for referential integrity, and also won't allow rollbacks to happen should an error occur during a transaction.  MyISAM is also not ACID compliant.  Problems with this may also only come out under load.
Answer: Changing the database engine wont help.
What you should understand is what is drupal semaphores. follow this link: https://www.drupal.org/project/flood_sem if you want to understand what semaphores are. In you case it means this table of semaphores which drupal depends on does not exist due to your misconfiguration during migrate or install. You will have to run drupal install script.
However, semaphores tables dont run on innoDB but myISAM since its a PHP process that calls a third party service for data like drupal theme forms, theme tables ect.
I hope u understand.
Answer: I ran into this same error message in moving Drupal 7 from one development site to another development site on my laptop. Upon checking the tables in the Drupal database I found that the full sql dump was not being imported (using Adminer and the "From server" option, adminer.sql).
Look for Drupal 7 database tables that come near the end of the dump alphabetically like:  user*, views*, webform*, workbench*, xmlsitemap* to see if it all imported.
I then used drush sql-cli < database.sql to import the sql dump into the Drupal database after dropping all tables with drush sql-drop.
Comment: Please don't double post answer across multiple questions. As the answer states, this is a duplicate question that should be flagged as such.
Comment: Sorry, I would have posted a comment and linked to the answer  on the other issue but since I do not have 50 points I cannot.


Is it appropriate for a study to ignore missing data?

Question: I am doing critical appraisal of a paper. The study has missing covariate data. The missing data is listed but it does not state what categories the data is missing? Is it appropriate to impute missing covariate data or was the study correct in just listing the amount missing and continuing with analysis.
Independent variable (self-reported sleep duration)
Dependent variable (Hypertension)
Missing covariates include alcohol consumption, caffeine, smoking, CVD, insomnia symptoms, depressive symptoms.
Comment: Welcome to Cross Validated! What do you mean by "ignore"? - using complete cases only? And what was the analysis they continued with? - a multiple regression? I think more details are needed for more than a generic answer to be given here.
Answer: If you data is missing at random (MAR), then the answer is possibly and you should be careful to adjust for the fact that you imputed the data (by using multiple imputation, say), which will inflate the variance adequately.
Otherwise, if you cannot assume that your covariates are missing at random, things can go wrong. Consider a simple case: heavy drinkers do not reply to your study and you have no patient with high alcohol consumption in your study. Suppose that alcohol affects sleep past a certain consumption level and bias your results. You would not detect this effect.
Comment: Thank you for your help! I basically need to figure out if it is missing at random and go from there.


default row one for one set of rows in sql server

Question: CREATE TABLE ContactInfo (
ID int IDENTITY(1,1) NOT NULL,
CompanyID int NOT NULL,
ContactName varchar(45) DEFAULT NULL,
IsPrimary bit DEFAULT NULL
PRIMARY KEY (id)
)

INSERT INTO ContactInfo (CompanyID,ContactName,IsPrimary) VALUES (1,'Vijay',1);
INSERT INTO ContactInfo (CompanyID,ContactName,IsPrimary) VALUES (1,'Amit',0);

ID  CompanyID   ContactName IsPrimary
1   1           Vijay       1
2   1           Amit        0

Whenever user adds, updates and deletes rows, for each company IsPrimary should be unique. I.e for each CompanyID there should be only one row that has IsPrimary = 1.
Conditions:

only one row should be IsPrimary = 1  for each CompanyID
all rows should not be IsPrimary = 0 for each CompanyID
if user deletes IsPrimary row then other row should be assigned IsPrimary = 1
when first time user enter the record user will select isprimary,  even if he forget our query should assign isprimary =1'
5 when entering onward second   record if he assign isPrimary=1 if isprimary exist in same company id then that record should be isprimary = 0'
6.if existing isprimary change 1 to 0 then other top 1 record under same company id that should be assign isprimary=1.'

I hope you understand my condition
i also put question in msdn  enter link description here
some body give near solution but it's working with all condition
CREATE TABLE ContactInfo (
ID int IDENTITY(1,1) NOT NULL,
CompanyID int NOT NULL,
ContactName varchar(45) DEFAULT NULL,
IsPrimary bit DEFAULT NULL
PRIMARY KEY (id)
)
GO

CREATE TRIGGER trg1  ON ContactInfo  AFTER INSERT, UPDATE, DELETE
AS
    --UPDATE ContactInfo SET IsPrimary=1 FROM ContactInfo JOIN inserted I ON I.CompanyID=.ContactInfo.CompanyID
    --for INSERT
    IF EXISTS(SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
       UPDATE T SET IsPrimary= CASE WHEN RN=1 THEN 1 ELSE 0 END
       FROM (SELECT ROW_NUMBER() OVER(PARTITION BY CompanyID ORDER BY (SELECT 1)) RN,IsPrimary
       FROM ContactInfo WHERE CompanyID IN(SELECT CompanyID FROM inserted)) T

    --for UPDATE
    ELSE IF EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted)
       UPDATE T SET IsPrimary= CASE WHEN RN=1 THEN 1 ELSE 0 END
       FROM (SELECT ROW_NUMBER() OVER(PARTITION BY CompanyID ORDER BY (SELECT 1)) RN,IsPrimary
       FROM ContactInfo WHERE CompanyID IN(SELECT CompanyID FROM inserted)) T

    --for DELETE
    ELSE
       UPDATE T SET IsPrimary= CASE WHEN RN=1 THEN 1 ELSE 0 END
       FROM (SELECT ROW_NUMBER() OVER(PARTITION BY CompanyID ORDER BY (SELECT 1)) RN,IsPrimary
       FROM ContactInfo WHERE CompanyID IN(SELECT CompanyID FROM deleted)) T
GO

--insert one row with is primary 0
INSERT INTO ContactInfo (CompanyID,ContactName,IsPrimary) VALUES (1,'Vijay',0);
--IsPrimary gets 1 actually
SELECT * FROM ContactInfo

--add one more row for the same company id 1 with IsPrimary=1
INSERT INTO ContactInfo (CompanyID,ContactName,IsPrimary) VALUES (1,'Amit',1);
--IsPrimary gets 0 actually
SELECT * FROM ContactInfo

--update the Isprimary to 1 for Amit
UPDATE ContactInfo SET IsPrimary=1 WHERE CompanyID=1 and ContactName='Amit'
SELECT * FROM ContactInfo

--delete Vijay whose IsPrimary=1
DELETE ContactInfo WHERE CompanyID=1 and ContactName='Vijay'
--Amit's Isprimary has been set 1
SELECT * FROM ContactInfo

Comment: You need to implement trigger. What have you tried? Can you show the code?
Comment: i am planing to do  like this  -- for new insert if not selected Primary
if not EXISTS(select isprimary from ContactInfo where CompanyID= 1 and IsPrimary = 1)
begin
 UPDATE ContactInfo
 SET     IsPrimary = 1
end
Comment: @naweez I don't really get you here. The trigger looks OK to me. Can you describe the case where it doesn't work?
Comment: You could just do a union for inserted and deleted tables without that confusing logic
Comment: The design of `IsPrimary` is inappropriate, you shouldn't rely on trigger to maintain the field and suffer from possible locking. Instead you add a `CreateDate` field and `ForcePrimaryDate` then calculate the `IsPrimary` on the fly from a view
Answer:
for each CompanyID there should be only one row that has IsPrimary =
  1.

To enforce this create a filtered unique index. The index is filtered on IsPrimary=1 and is unique on CompanyID
Something like this:
CREATE UNIQUE NONCLUSTERED INDEX UIX_IsPrimary ON ContactInfo
(
    CompanyID ASC
)
WHERE (IsPrimary=(1))
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON,
ALLOW_PAGE_LOCKS  = ON)
ON [PRIMARY]

This enforces condition 1
I suggest you enforce conditions 2,3,4 from your application or via a storedp procedure. Triggers often have unanticipated side effects
Comment: Trigger is the only thing that will do it automatically but they usually turn into a maintenance nightmare.
Comment: that i can prevent the used through constrain , but i need automatically.
Answer: Provided trigger does the job partially, but does not allow you to control how to handle what happens to IsPrimary flag when you delete the last from the group or have multiple IsPrimary-s due to INSERTs or UPDTEs.
In order to simplify testing a little bit, I have changed ContactInfo a little bit - IsPrimary get a default of 0, since all but one record have 1 here:
-- drop table ContactInfo
CREATE TABLE ContactInfo (
    ID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyID int NOT NULL,
    ContactName varchar(45) DEFAULT NULL,
    IsPrimary bit NOT NULL DEFAULT(0)
)
GO

Now, the new trigger:
Basically, I am trying to handle the following cases:
no primary in group - add to one in the group
more than one primary in the group
   if primary comes from inserted, use that
   else use from actual table
 alter TRIGGER trg1  ON ContactInfo  AFTER INSERT, UPDATE, DELETE
 AS
 BEGIN
    DECLARE @Debug BIT = 1

    -- ContactInfo now contains data as if operation is done
    CREATE TABLE #tmpTrg1 (CompanyID INT PRIMARY KEY, MinId INT, PrimaryCount INT)

    -- if primary count for a company is 1, it is fine, no need for extra operations
    INSERT INTO #tmpTrg1
    (CompanyID, PrimaryCount, MinId)
    SELECT CompanyID, COUNT(IsPrimary), MIN(ID)
    FROM ContactInfo
    GROUP BY CompanyID
    HAVING COUNT(*) <> 1

    IF (@Debug = 1)
        select '#tmpTrg1' AS '#tmpTrg1', * from #tmpTrg1

    -- no primary count
    -- try to avoid putting IsPrimary back again if caller wants to get rid of it
    update CI
    set IsPrimary = 1
    FROM ContactInfo CI
        JOIN #tmpTrg1 T ON T.CompanyID = CI.CompanyID AND T.MinId = CI.ID
    where ISNULL(T.PrimaryCount, 0) = 0 AND
        ID NOT IN (SELECT ID FROM inserted)

    -- still no primary, choosing one from each group
    ;WITH CntCte AS (
        SELECT CompanyID, MIN(ID) AS MinId
        FROM ContactInfo
        GROUP BY CompanyID
        HAVING MAX(CAST(IsPrimary AS INT)) = 0)
    update CI
    set IsPrimary = 1
    FROM ContactInfo CI
        JOIN CntCte C ON C.CompanyID = CI.CompanyID AND C.MinId = CI.ID

    -- too many primary counts - removing IsPrimary from all except one. A primary from inserted takes precedence
    ;WITH InsCte AS (
        SELECT CompanyID, MIN(ID) AS MinId
        FROM inserted CI
        GROUP BY CompanyID),
    MinInsCte AS (
        SELECT T.CompanyID, ISNULL(InsCte.MinId, T.MinId) AS MinId
        FROM #tmpTrg1 T
            LEFT JOIN InsCte ON InsCte.CompanyID = T.CompanyID AND T.PrimaryCount > 1)
    UPDATE CI
    SET CI.IsPrimary = 0
    FROM ContactInfo CI
        JOIN MinInsCte Ins ON Ins.CompanyID = CI.CompanyId AND Ins.MinId <> CI.ID
END
GO

And the tests:
truncate table ContactInfo
go

-- first records should be primary
INSERT INTO ContactInfo (CompanyID,ContactName) VALUES (1,'Some name 1'), (2, 'Some name 2')
SELECT 'first records', * FROM ContactInfo
GO

-- multiple insert - should not get primary
INSERT INTO ContactInfo (CompanyID,ContactName) VALUES (2,'Vijay'), (3, 'Other name'), (2, 'Extra name')
SELECT 'multiple insert', * FROM ContactInfo
GO

-- update should not affect primary
update ContactInfo SET ContactName = 'new name for non primary #1' where CompanyID = 2
SELECT 'update non primary', * FROM ContactInfo
GO

update ContactInfo SET ContactName = 'new name for primary' where CompanyID = 1
SELECT 'update primary', * FROM ContactInfo
GO

-- deleting existing primary
delete ContactInfo WHERE ID = 2
SELECT 'delete primary', * FROM ContactInfo
GO

-- try to remove primary from existing record
update ContactInfo SET IsPrimary = 0 where ID = 1
SELECT 'remove primary', * FROM ContactInfo

-- multiple deletes
DELETE ContactInfo
WHERE CompanyID IN (2, 3)
SELECT 'multiple delete, including primary', * FROM ContactInfo

-- insert another record with primary
INSERT INTO ContactInfo (CompanyID,ContactName, IsPrimary) VALUES (2,'Other primary', 1)
SELECT 'insert another record with primary', * FROM ContactInfo
GO

-- try to force primary for multiple records
INSERT INTO ContactInfo (CompanyID,ContactName, IsPrimary) VALUES (1,'Vijay #2', 1), (1, 'Other name #2', 1)
SELECT 'multiple insert with primary', * FROM ContactInfo
GO

It is quite convoluted, so I would try to this from the application, as already suggested in one answer.
Comment: you are predinfen isprimary , i want user has to select while inserting & updating. if user deleted isprimary record , you can assign  isprimary top one record.
Comment: The last insert from the tests shows that IsPrimary can be specified by the user. IsPrimary is on the first record, user tries to insert two IsPrimary values. The first record is no longer primary (the second is). I will also add a test for simple insert with IsPrimary to show that IsPrimary can be moved in a deterministic way.
Comment: I have finally seen what the question really wants from us, so I have changed the trigger to act accordingly. I am still not sure that it matches all the scenarios, but it allows to configure how the IsPrimary should behave when it does not exist in the group or there are duplicates.


multiplication for lists in python

Question: I know there is something obvious that I am missing but I would rather clear my confusion than to mug it up.
why does the following code:
[1]*5
return
[1,1,1,1,1]
and not
[5]
or
[[1],[1],[1],[1],[1]]
Comment: Say you have a list, `l`. Then `3*l` is equivalent to `l + l + l`
Comment: In other words, list addition is equivalent to concatenation. So multiplication is naturally defined in those terms
Answer: Multiplication is defined for sequences in general, not just lists, regardless of the type of the contained values. Sure, [1] * 5 -> [5] makes sense for a list of int, but it's nonsensical for a list of str, or a str by itself.
They wanted a generic sequence handler that worked for sequences of all types, so they defined it as repeated concatenation, rather than element-wise arithmetic. As juanpa mentions in the comments, this makes for a consistent definition: seq + seq is concatenation, so seq * int is just seq + seq repeated int times (well, seq is repeated int times, with four virtual concatenations), the same way inta * intb is just inta + inta repeated intb times.
If you want element-wise arithmetic, take a look at numpy arrays.

multiplication for lists in python


Product of all elements in a group

Question: I'm reading Aluffi's "Algebra: Chapter 0", and have some difficulties with exercise II.1.8:
Let G be a finite group with exactly one element f with order 2. Prove that $П_{g\in G}(g)=f$
I've proved it for abelian groups, is it really true for all groups?
Comment: @MoisheKohan thx I've been trying to find it here for hours
Comment: Just look at the list of questions under the header "related" on the right-hand side of the page with your question. I was sure, I saw this question before and, sure enough, it was listed. Most duplicates can be found this way.
Comment: @MoisheKohan thx it works, didn't know about it
Answer: There is a very neat but deep result here that goes a step further.  Let $G$ be a finite group of order $n$, say $G=\{g_1, g_2, ..., g_{n-1}, g_n\}$ and define $\wp(G)=\{g_{\sigma(1)} \cdot g_{\sigma(2)} \cdot \cdot \cdot g_{\sigma(n-1)}\cdot g_{\sigma(n)}: g_i \in G, i=1,... ,n$ and $\sigma \in S_n\}$, in other words $\wp(G)$ is the set of all possible products of $n$ different elements of $G$. (Of course the result of such product depends on the order of the elements, $G$ does not have to be abelian here!). Let $S$ be a Sylow $2$-subgroup of $G$. If $S$ is non-cyclic or $\{1\}$ (that is $|G|$ is odd), then $\wp(G)=G'$. If $S$ is cyclic, then $\wp(G)=xG'$, where $x$ is the unique element of order $2$ of $S$.
Comment: it's very interesting, but I don't understand what $G'$ means. If it s the commutator, is it trivial in our case?
Comment: It is the *commutator* subgroup of $G$, so $G'=\langle [x,y]: x,y \in G \rangle$. Note that $G'$ is the *smallest* normal subgroup of $G$ such that the quotient is abelian.

Product of all elements in a group


Shortest distance as measured in norm $||\cdot ||$ from point to a sphere in norm $||*||$

Question: I recently found this theorem, which is used in some clustering algorithms:
Let $x,v \in \mathbb{R}^p$, $r>0$, $||\cdot ||_{\ast}$ be a given norm on $\mathbb{R}^p$ and $\partial B_{||\cdot||_{\ast}}(v,r) = \{ y\in\mathbb{R}^p: ||y-v||_{\ast}=r \}$ be the closed ball of radius $r$ centered at $v$. Then the shortest distance, as measured by $||\cdot ||_{\dagger}$, from any point in $\partial B_{||\cdot||_{\ast}}(v,r)$ to $x$ is $\left|\ ||x-v||_{\ast}-r \right|.$
I know that this holds for $||\cdot ||_2,$ but how would one prove that this holds for any two pairs of norms $||\cdot ||_{\ast}$ and $||\cdot ||_{\dagger}$?
I've tried tracking down the original article, because all the articles I've seen that have cited it do exactly that, just cite it, without giving the proof.
This isn't homework or anything like that, I'm just curious as to what approach one could use when trying to prove this?
EDIT: Source of this claim: Page 65.
Now that there is a counterexample in one of the answers, I suppose that there is actually only one norm here. I apologize for the confusion, but as you will see from the source, the two norms are marked differently, which led me to the conclusion that they are not the same.
Comment: You can use norm subscripts like $\ast$ or $\dagger$
Comment: Your question would be easier to understand if you'd put subscripts to distinguish different norms.
Comment: I didn't use subscripts because I thought they might make it seem like a certain norm the $p$-norm is, or something similar. If you have suggestions for subscripts, please let me know. Also, the norm which is used in $||y-v||$ and $||x-v||$ is the $||*||$, the norm $||\cdot ||$ is the one in which the distance between the point and the sphere is measured. @SeverinSchraven
Comment: As how I interpret this, is that $\| \cdot \|_{\dagger}$ is just notation for $\| y \|_{\dagger} := \inf_{y \in \delta B_{\| \cdot \|_{*}}(v,r)} \{ \| x-y \|_{*}\}$. So you do not have two pairs of norms, but rather one norm and a function of that norm and some parameters $v$ and $r$, denote by $\| \cdot \|_{\dagger}$.
Comment: @Hetebrij No, there are two different norms here. However, now that you posted this, it made me think differently about the norms. Could it be that only the sphere is given in one norm and the other norm is the one which we are trying to minimize?
Comment: Is it possible that you changed during your last edit $\vert \ \Vert x - v \Vert_{\dagger} - r\vert$ to $\vert \ \Vert x - v \Vert_{\ast} - r\vert$?
Comment: Thanks for the new notations. Do you have a source for the claim?
Comment: @SeverinSchraven As you will see from the source of the claim which I just added, you can't really tell which norm is which, so my edit was made in the way I thought it should be.
Comment: @LaurentDuval Source added.
Comment: @T_M OK. I have added another source that suggests there was only one norm.
Answer: Your claim is wrong even if one of the norms is the Euclidean norm. Take $p=2, \ r=1, \ v=(0,0)$ and $x=(2,2)$. We take the following two norms
$$ \Vert (y,z) \Vert_1 := \sqrt{y^2+z^2}, \quad \Vert (y,z) \Vert_2:= \frac{1}{2} \max\{\vert y \vert, \vert z \vert \}.$$
Then
$$ \min_{\Vert w \Vert_1=1} \Vert w - x \Vert_2 \geq  \frac{1}{2} > 0 = \vert \ \Vert x \Vert_2 - 1 \vert = \vert \ \Vert x - v \Vert_2 - r\vert.$$
Where we used
$$ \Vert x \Vert_2 =  \Vert (2,2) \Vert_2 = \frac{1}{2}\max\{ \vert 2 \vert, \vert 2 \vert \} = 1.$$
The first inequality follows from the following considersation.
$$1= \Vert (w_1, w_2) \Vert_1 \Rightarrow 1 = 1^2 = w_1^2 + w_2^2 \Rightarrow \max \{ \vert w_1\vert, \vert w_2 \vert \} \leq 1.$$
Thus, if $\Vert (w_1, w_2) \Vert_1 = 1 $, then
$$ \Vert (w_1, w_2) - x \Vert_2  = \frac{1}{2} \max \{ \vert w_1 - 2\vert, \vert w_2 - 2 \vert\} =\frac{1}{2} \max \{ 2- w_1, 2-w_2\}
\geq \frac{1}{2}.$$
Comment: I literally have no idea how you calculated the norms. Could you clarify?
Comment: @T_M I hope this helps.
Answer: With the same norms a demonstration uses the following. Using norm subadditivity, for any $b$ on the sphere:
$$\|b\| \le \|b-x\|+  \|x\|$$
and
$$\|x\| \le \|x-b\|+  \|b\|$$
so all in all:
$$\|x-b\| \ge \max(\|b\|-\|x\|,\|x\|-\|b\|) = |\|x\|-r|\,.$$
Unfortunately, this does not seem to work for different norms in general. Take $ p=2$, a $l_q$ and a $l_r$ two norms, $q,r \ge 1$. Take $v$ at the origin (because it plays little role here), $r=1$, $x=(1,1)$ on the diagonal. Then the minimum $l_r$ norm to the $l_q$ ball is $m=2^{1/r}(1-1/2^{1/q})$. And your formula gives $n=2^{1/q}-1$.
The two quantities are equal if and only if $ q =r$. Note that the above generalizes with higher dimension $p\ge 2$.
[EDIT] I have just found a paper by Bezdek in 1995: Shell-prototype clustering models. The theorem given (cropped for the record) is:

Apparently there is only one "given" norm. I guess that the $\|*\|$ stands for a wildcard-type notations meaning "any argument", while $\|\cdot\|$ is the functional notation.
Comment: I think this works only if the two norms coincide.
Comment: I might have  fooled myself with the norm notation. Counter example with $l_2$ and Chebychev norm in mind.
Comment: I edited the norm notation. We have the space $(\mathbb{R}^p,||\cdot ||_{\ast})$, but the problem of finding the distance between the point and sphere is to be measured in $\\\cdot ||_{\dagger}.$
Comment: Is there a full text of the article with the proof? I couldn't find it anywhere, and my IEEE membership expired.
Comment: @T_M I cannot share it, it is copyrighted materials. There is no proof in the paper.
Comment: I understand. Then could you elaborate a bit more on how to proceed with the proof you gave when you defined $b$? @LaurentDuval
Comment: @T_M Seems simpler, I have modified the proof


Typeahead.js using array object, reloading source on every onkeyup

Question: I´m trying to use typeahead for making a complex query easier to process. So the idea is to use typeahead to show a list of options and when one is choosen, set the input with the label of the choosen item and set an input hidden with the id of that item. There is an other situation to be resolved, every time a letter is enter, the source of typeahead change, cause these fields got 40000 options aprox., so the service used got a top 10 filter.
html code:

                      <input class="typeahead" type="text" id="iCliente" onkeyup="actualizarArray();">

<input type="hidden" id="selectedId">

script code:
function actualizarArray()
    {
        var clientesProcesados;

        $('#bloodhound .typeahead').typeahead('destroy');

        var urlTypeahead = 'http://localhost:8082/contratantes/search/findTop10ByNombreContaining?nombre=' + $('#iCliente').val();

        $.ajax({
            url: urlTypeahead,
            type: "GET",
            dataType: 'json',
            success: function (data){
                //alert('entro');
                //TODO procesar JSON para que bloodhound lo pueda levantar
                var arrayClientes = data._embedded.contratantes;
                var arrayClientesProcesados = [];

                for(var i in arrayClientes)
                {
                    //var clienteStr = /*'{\"id\":\"' + arrayClientes[i].id + '\",\"nombre\":\"'*/ + arrayClientes[i].nombre /*+'\"}'*/;
                    arrayClientesProcesados.push(arrayClientes[i].nombre);
                }

                clientesProcesados = new Bloodhound({
                      datumTokenizer: Bloodhound.tokenizers.whitespace,
                      queryTokenizer: Bloodhound.tokenizers.whitespace,
                      local: arrayClientesProcesados
                });

                $('#bloodhound .typeahead').typeahead({
                      hint: true,
                      highlight: true,
                      minLength: 1
                    },
                    {
                      name: 'clientesProcesados',
                      source: clientesProcesados
                    });

                $('#iCliente').focus();
            }
        });
    }

The problem is, that when the array of objects is set as source, typeahead dont show any option, so I dont know what i m doing wrong. This code, just showing arrayClientes[i].nombre, works fine; and every time onkeypress is fired, the source update works perfectly. So I'm missing the part where typeahead source is set with the array of objects, showing arrayClientes[i].nombre only, and then making the onselect event set the hidden input with the id of the selected item.
Can any body help me?
Comment: Try calling `clientesProcesados.initialize()` before `.typeahead({})` , setting `source` to `clientesProcesados.ttAdapter()`
Answer: I resolved!!!
function actualizarArray()
    {
        var clientesProcesados;

        $('#bloodhound .typeahead').typeahead('destroy');

        var urlTypeahead = 'http://localhost:8082/contratantes/search/findTop10ByNombreContaining?nombre=' + $('#iCliente').val();

        $.ajax({
            url: urlTypeahead,
            type: "GET",
            dataType: 'json',
            success: function (data){
                var arrayClientes = data._embedded.contratantes;
                var arrayClientesProcesados = [];

                for(var i in arrayClientes)
                {
                    arrayClientesProcesados.push({
                        id:arrayClientes[i].id,
                        nombre:arrayClientes[i].nombre
                    });
                }

                clientesProcesados = new Bloodhound({
                      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('nombre'),
                      queryTokenizer: Bloodhound.tokenizers.whitespace,
                      local: arrayClientesProcesados
                });

                clientesProcesados.initialize();

                $('#bloodhound .typeahead').typeahead({
                      hint: true,
                      highlight: true,
                      minLength: 1
                    },
                    {
                      name: 'clientesProcesados',
                      displayKey: 'nombre',
                      source: clientesProcesados.ttAdapter()
                    });

                $('#iCliente').focus();
            }
        });
    }

    $('#bloodhound .typeahead').bind('typeahead:selected', function(obj, datum, name) {
        $('#selectedId').val(JSON.stringify(datum.id));
    });

Comment: any help on this question http://stackoverflow.com/questions/35320812/duplicate-records-coming-in-typeahead-search


Translating Sheet Music to Guitar Tabs (without any software help (: )

Question: I have been playing guitar for a few months and have grown to love it. I played sports and participated in 0 fine arts growing up, so this is all very new to me. I was excited to initially learn guitar tabs since they are so easy to read, but I've decided it is finally time for me to delve into learning sheet music and translating it into tabs for practice. As an exercise, I am curious in translating part of a score from a video game. The part I decided to start translating (along with the notation) can be found here (credit goes to 8-Bit Music Theory for the video content and Nintendo for the music itself). I am only interested in the top bar (the one that gets labeled as running up A lydian and subsequently down D lydian).
I believe I have derived the correct notes which are in the key of A, as seen below (this is just the first two measures) (I am also unsure how to depict stacked notes/chords when writing them out like this, so I apologize if this is incorrect.)
C - C - D♯ - D♯ - E - E - F -  F -  G - G - A - A - B - C - D♯
A - A - B -  B -  C - C - D♯ - D♯ - E - E - F - F - G - A - B
EDIT: I just came across this site which names chords based on the notes. So in my example it would be Am Am Asus2 Asus2... etc., but that is besides the point of this question.
Anyways, assuming I have the correct notes, I have tried to put them into tabs, but I can't really find anything that sounds "right".

Should I stay on the same two strings? (I am ignoring note length and any other advance tab notation, again for the sake of example.)

E|------------------------------------------------------
B|------------------------------------------------------
G|------------------------------------------------------
D|------------------------------------------------------
A|--3--3--6--6--7--7--8--8--10--10--12--12--14--15--18--
E|--5--5--7--7--8--8--9--9--12--12--13--13--15--17--19--

I would assume obviously not, as this requires too much hand movement and sounds "stale" all being on the same two strings.

Do I incorporate multiple strings that aren't consecutive?

E|--5--5--7--7--8--8--11--11--12--12--13--13--15--17--19--
B|--------------------------------------------------------
G|--5--5--8--8--9--9--10--10--12--12--14--14--16--17--18--
D|--------------------------------------------------------
A|--------------------------------------------------------
E|--------------------------------------------------------

Albeit sounding a bit nicer, I would also assume not since this is way too hard to play (at least for me lol) in rhythm and still incorporates a lot of hand movement.

Do I stick in one general area, moving across multiple strings?

E|-----------------------------------------------
B|-----------------------------------------------
G|--------------------------------------4--5--8--
D|--------------------3--3--5--5--7--7--5--7--9--
A|--3--3--6--6--7--7--6--6--7--7--8--8-----------
E|--5--5--7--7--8--8-----------------------------

Or something different?

General questions:

How do I know which note should go on top? ie

E|-----
B|-----
G|--8--
D|--9--
A|-----
E|-----

or

E|-----
B|--4--
G|--4--
D|-----
A|-----
E|-----

How do I know when to move to the next string?
Do I completely ignore the stacked notes/chords and play these as individual notes in a tighter area/shape higher on the fretboard? (This question I am especially intrigued by)

etc, etc...
It seems like there are so many different ways to turn sheet music into tabs. Is it a "feel" sort of thing? Do you experiment around until you land on something that sounds nice?
This is my first question on this site so I hope it is appropriate, in-depth, and valid while clearly conveying what I have tried. I understand this is a loaded post... so if someone experienced just wants to post their take on the tabs I could try and figure these questions out myself.
Thanks!
Note: I am playing on electric
Comment: @bismo, thanks. What I recognize time and again is that guitarists tend to recommend using leadsheets instead of tabulatures. Though a reason is rarely given, if you think about it, what you do is to see something (notes, tabs, chord-letters ...) AND to translate it into finger-motion. It's just the same mental-mechanical process as reading written text out loud. // The fret position can also be indicated in lead sheets, e.g. by fretboard symbols, or simply by a number indicating the barre. // The fret to chose depends on sound, playability, previous and next notes etc.
Comment: If you want to learn to read sheet music for guitar, transcribing it into tablature will actually impede your progress. Read sheet music only that has no tabs and play guitar from it, forget about tabs while you're learning to read sheet music.
Comment: Do not waste your time using tab as an an intermediator. Tab is only as good as the writer, some of whom are still wet behind the ears. Immerse yourself straight into the dots, and save time in the long run. Yes, it may take a little longer to get results, but you'll benefit from doing just that.
Comment: Hm, if you could ask only one question: which one is it?
Comment: @MS-SPO What an experienced musician's take on the tabs would be. Then I could try to piece together the answers to the rest of my questions from there.
Answer: As you have yourself admitted, the question is a bit too broad, but I have a couple of thoughts on it anyway.
First of all, learning standard notation is a good step towards better musicianship, and it's also a must if you want to play more complicated things on the guitar. BUT:
Firstly, I wouldn't recommend translating standard notation into tabs. The reason is that if you're going to learn to read music at all, you want to achieve at least a certain level of fluency in it — you look at the notes and you should more or less immediately see what is going on there and/or be able to play it on your instrument. If you translate the scores into tabs, you will never reach such fluency since you never get to practice it.
It's as if you wanted to be able to read English texts aloud correctly, and you decided to grab some dictionaries and painstakingly rewrite many texts phonetically, so that you could easily read them. You may do this many times and you still won't be good at reading English.
Second, tabs should be avoided if possible (in my humble opinion with which you may disagree). Yes, they're good for people who cannot read music and who want to learn simple tunes fast. They're mostly awful at everything else. As soon as any more complicated rhythm or voice leading occurs, the tabs become a nightmare to write and read. And they force certain fingering upon you, with which you may disagree. So (in my opinion!) you should leave tabs behind as soon as you can.
Third, if you want to learn to play from scores on your guitar, I would recommend playing pieces that are actually meant for guitar. There are loads of music written in standard notation that are written for the instrument. In your example, you have a lot of stacked thirds. They can be very naturally played on the piano, but it's quite hard to play them nicely on the guitar — they're just not that well suited to the instrument. Of course it can be done, but for a beginner it's probably more pain than it's worth (and not only for a beginner — you're not going to find them in many of more advanced pieces either).
Fourth, you haven't read the score correctly. There is a key signature of three sharps (A major) that makes each F into a F#, each C into a C# and each G into a G# (unless cancelled by a natural). So you play wrong pitches, and that's why you're not getting what you want. Written correctly, it should be C# C# D# D# E E F# F# etc., and A A B B C# C# D# D# etc.
Moreover, you play the notes in wrong octaves. In your first example, you play an octave lower than what's written in the score. In the second example, the note on the G string is in the correct octave (but you should play on 6th fret, since it's a C#), but the A is an octave higher than it should be (you should play it on the 4th string, 7th fret). This changes the relations between the notes considerably (the formal name for this particular thing is "inversion") and you get something quite different.
Fifth — when it comes to fingering (i. e. choosing what tone to play on which string with which finger), it's more or less a matter of taste. In most cases, there are multiple "solutions". Pick the one that you find the most comfortable for you. With more time spent with guitar, you will also find that the thicker strings have different "color" than the thinner ones, and so playing high up the neck on thicker strings will sound differently than playing lower on the neck on thinner strings. That's all up to your consideration. Just stick with what sounds good and feels comfortable to play.
Comment: @bismo — the dots in the score contain precise information about pitches, including the octave, so nothing special. Regarding the octaves: how do you find the notes on fretboard? Do you by any chance use a chart like this: https://cdn.musiciantuts.com/wp-content/uploads/2016/05/guitar-fretboard-notes-with-sharps.png ? If so, then your problem is that the notes in the score tell you name + octave, but this kind of a chart does not show the octaves, so you conflate them together.
Comment: Thanks for the concise, in-depth answer. It appears I indeed forgot to include the sharps from the key signature, leading to an incorrect reading. Thanks for pointing this out. Per the second part of your fourth point, how could you tell I am playing the incorrect octaves from the score? Is there any special notation I'm not noticing? And how can you tell which note on a guitar relates to which octave? Of course one note 12 frets higher on the same string is an octave higher, but how can you compare octaves between the same note on different strings?


Correct chord name for Am(maj7)add9?

Question: Given the chord notes A-C-E-G#-B, what is the correct chord name assuming the song is in the key of Am?   It is an E/Am polychord and the dissonance between the C and the B is the sound I'm seeking, so simply writing this as E/A doesn't really work.  I could write it as Cmaj7#5/A, I suppose, but that looks weird.  I believe it is an Am(maj7) with an added ninth but I'm not sure exactly how to write this on a chord chart.
Answer: This chord is called Am maj9 ("A minor major 9"). On a chart it would often be written just a Am maj7, which describes the basic chord quality. The additional tension (9) would be left at the discretion of the musicians.
Note that major 7th chords are often written using the triangle symbol Δ. This is also true for minor chords with a major seventh (and a major ninth): AmΔ7, or AmΔ9.
The modifier "add 9" is only used if the 7th scale degree is not part of the chord, e.g., Am(add9) being A-C-E-B.

Correct chord name for Am(maj7)add9?


How To Set Different Icons for an AlertDialog?

Question: for example if we get an error then it show appropriate icon for this behavior like wrong and right icons.
if(condition true)
{
  //here i need set right icon
}
if(condition false)
 {
 //here i need set wrong icon
AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
ad.seticon();//how to set for different behavior

Comment: Both the answers give almost the same advice, you should accept one of the answers.
Answer: You can make an int to hold the drawable id for false/wrong (as a default value), then if it's true/right, change what resId points to. If you don't want an icon as default, make resId equal to 0. Then set the icon after making the AlertDialog.
int resId = R.drawable.false;

if(condition == true)
{
  resId = R.drawable.true;
}

 //here i need set wrong icon
AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
ad.setIcon(resId);//how to set for different behavior

Of course, make sure that you have true and false pictures in your res/drawable folder.
Answer: Set resource id of correct/wrong image and just call the method and show the dialog with appropriate icons.
int res_id=0;

  if(condition true)
  {
       res_id = R.drawable.correct;
       myDialog(res_id);
  }

 if(condition false)
  {

        res_id = R.drawable.wrong;
        myDialog(res_id);
   }

  void myDialog(int resId){

        AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
        ad.setIcon(resId);

   }


When do you use the Dickey Fuller Test and the Ljung-Box Test?

Question: When do you use the Dickey Fuller Test and the Ljung-Box Test?
They seem to serve the same purpose?
I think that the Durbin-Watson statistics just checks for autocorrelation at lag 1.
Answer:
The Dickey-Fuller test addresses the question of whether the time series of interest has a unit root.
The Ljung-Box and the Durbin-Watson tests help assess whether the time series of interest is autocorrelated.

These are two different questions. According to the tag description of a unit root,

A unit root is a property of a non-stationary time series which can lead to spurious regressions and wrong inference. A series
$$ y_t = y_{t-1} + e_t $$
with $e_t \sim i.i.d.(0,\sigma^2)$* has a unit root if it can be expressed as $(1-L)y_t = e_t$
where $L$ is the lag operator. Then the characteristic equation of the above process has one unit root. A property of the unit root is that when an $I(1)$ autoregressive process is first differenced, it becomes an $I(0)$ process, i.e. it will be stationary.

According to the tag description of autocorrelation,

Autocorrelation (serial correlation) is the correlation of a series of data with itself at some lag.  For example, if a given value were higher than average, it might be more likely than not that the next value would also be higher than average; if so, there is a positive autocorrelation at lag 1.
The autocorrelation for a time series, between times $s$ and $t$ is defined as:
$$R(s,t) = \frac{\mathbb{E}[(X_t - \mu)(X_s - \mu)]}{\sigma_t \sigma_s}$$
where $\mathbb{E}$ is the expected value operation.

Some differences between the Ljung-Box (LB) and the Durbin-Watson (DW) tests

LB tests a joint null hypothesis of autocorrelation at a set of lags being equal to zero, while DW tests a null hypothesis of autocorrelation at a single lag being equal to zero.
LB test can be applied to any selected group of lags (though usually the first $k$ for some natural number $k$), while DW tests autocorrelation at lag 1 specifically.

*It is enough that $e_t$ is a stationary process or an I(0) process which are almost the same.
Answer: In a simpler terms, we can say the Unit Root tests (including KPSS test or Augmented Dickey Fuller (ADF) test) are used to test if the the time series of interest is non-stationary or not. If it is, we keep differencing the time series until we have a stationary time-series (usually maximum number of differencing is 2).
The main idea of differencing is to help stabilize the mean of a time series by removing changes in the level of a time series, and therefore eliminating (or reducing) trend and seasonality. In that case, the transformed time series is ready for the next step which is regression.
On the other hand, Portmanteau tests (including Box-Pierce test or Ljung-Box test (more accurate)) are used to see if the model trained is ready for inferencing and forecasting meaning that the model has been able to capture all of the trend and seasonality within a reasonable threshold or not. In other words, they test if the residuals of the trained model is a white noise (i.e. normal distribution (0, 1)).
It is interesting to note that if there are a few significant spikes in the ACF, and the model fails Portmanteau tests but it can still be used for forecasting, but the prediction intervals may not be accurate due to the correlated residuals.
Comment: -1. It can be unfortunate to simplify as you do, since presence of a unit root implies nonstationarity, yet nonstationarity does not imply presence of a unit root. Moreover, differencing is unwarranted in absence of a unit root. Consequently, the idea of using differencing to remove trend or seasonality is highly questionable. Your interpretation of portmanteau tests is also a bit misleading. They have to do with autocorrelation which may or may not be caused by trend or seasonality.


Finding $P(X_{1} = 1 \mid X_{1} + X_{2} + \cdots + X_{n} = m)$

Question: Suppose we have sequence of random variables $\{X_{i}\}$ This is a sequence of Bernoulli trials. Each $X_{i} = 1$ with probability $p$ with $0$ with probability $1-p$. Find  $P(X_{1} = 1 \mid X_{1} + X_{2} + \cdots + X_{n} = m)$.
I used conditional probability:
$$\frac{P(X_{1} = 1, X_{1} + \cdots + X_{n} = m)}{P(X_{1} + \cdots + X_{n} =m )} = \frac{P(X_{1} = 1) P(X_{2} + \cdots + X_{n} = m - 1) }{{n\choose m} p^{m}(1 - p)^{n - m}} $$
$$= \frac{p \cdot {n-1\choose m-1} p^{m-1} (1 - p)^{n - (m - 1)}}{{n\choose m} p^{m} (1-p)^{n-m}} $$
I'm not sure how to compute the top. Can someone help me please?
Answer: If the $X_i$ are independent then the numerator is $$P(X_{1} = 1, X_{2} + \cdots + X_{n} = m-1)=P(X_{1} = 1)\,P(X_{2} + \cdots + X_{n} = m-1)$$ which you can state in the same binomial way
Rather more directly, given $m$ of the $n$ $X_i$s are $1$ then by symmetry the conditional probability that $X_1=1$ is $\dfrac m n$
Comment: I think $m/n$ is right, but how come what I wrote in the original post doesn't simplify to that?
Comment: You wrote $\frac{p \cdot {n-1\choose m-1} p^{m-1} (1 - p)^{n - (m - 1)}}{{n\choose m} p^{m} (1-p)^{n-m}}$ when you should have written $\frac{p \cdot {n-1\choose m-1} p^{m-1} (1 - p)^{(n-1) - (m - 1)}}{{n\choose m} p^{m} (1-p)^{n-m}}$.  You can then simplify to $\frac{{n-1\choose m-1}}{{n\choose m}} =\frac{\frac{(n-1)!}{(m-1)!(n-m)!}}{\frac{n!}{m!(n-m)!}} = \frac{m}{n}$


AVPlayer: Playing a "on the fly" Transcode Audio file in Swift

Question: I am working on a project that implements the OpenHome library in swift. I am working on the Renderer provider side which mean that Proxies send media item URLs within the same network for playing. The app after getting a url needs to set the AVPlayer and play.
The URLs provided are like:

http://192.168.1.123:8088/ext/orig/audio/2249.flac
http://192.168.1.123:8088/ext/trans/audio/2249.mp3

If the URL contains "orig" means that the file matches with the extension.
On the other side, If the URL contains "trans" means that the file provided will match the extension but it will be served on the fly as it is being converted.
This technique works with Sonos, Android and Chrome browsers when I enter the URL. However it does not work with neither iOS and Safari (Considering I am doing it right).
I am attaching a test ViewController that handles the process
import UIKit
import AVFoundation

class ViewController: UIViewController {

    private var avAudioPlayer:AVPlayer!
    private var avAudioSession:AVAudioSession = AVAudioSession.sharedInstance()

    override func viewDidLoad() {
        super.viewDidLoad()

        try! avAudioSession.setCategory(.playback, mode: .default, options: [])
        try! avAudioSession.setActive(true)

        let urlString = "http://192.168.1.123:8088/ext/trans/audio/2249.mp3"
        let url = URL(string: urlString)!
        avAudioPlayer = AVPlayer(url: url)

        avAudioPlayer?.addObserver(self, forKeyPath: "status", options: [], context: nil)

    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if keyPath == "status"{

            switch avAudioPlayer.status{
            case .readyToPlay:
                print("Hey: Ready To Play")
                avAudioPlayer.play()
            case .failed:
                print("FAILED OH Nooo!")
            case .unknown:
                print("Something went wrong but ...")
            }

        }

    }

}

NSAllowsArbitraryLoads is set to true

I attach some status data:
print("A Reason = \(String(describing: avAudioPlayer.reasonForWaitingToPlay?.rawValue))")
-->A Reason = "AVPlayerWaitingWhileEvaluatingBufferingRateReason"

print("TIME Control Status = \(avAudioPlayer.timeControlStatus.rawValue)")
-->TIME Control Status = 1

Thank you.
Answer: Turns out that the provider side was not compatible with Apple media services. AVPlayer will actually handle it by it self.

AVPlayer: Playing a “on the fly” Transcode Audio file in Swift


Running PLINQ on Inherited Entities throws AccessViolationException

Question: I came across a bottleneck while testing an application that interfaces with a SQL-Compact 3.5 database with EF.
Usually, when I come across a bottleneck like this, I rework the linq query to reduce the number of linq queries done because re-running the same linq query a dozen times on a database filled with thousands of entries creates a bit of overhead. Then, I use plinq to speed up instantiation time.
Doing this has worked fairly well until I tried to do this with the ShapeEntities table.
The ShapeEntity is an abstract entity which works as the base class for other entities that are nearly identical to each-other. I can't run this with the AsParallel() method.
HashSet<Guid> keys ...

var x =
    from shape in model.ShapeEntities.AsParallel()
    where keys.Contains(shape.ImageKey)
    select shape;

List<ShapeEntity> shapes = new List<ShapeEntity>(x);

If I were to remove the AsParallel() from the code above, the query takes about 1.4 seconds to execute when we put it in the list. With the AsParallel() method, I get an AccessViolationException after about 40 seconds. It never gets past instantiation.
Does anyone have any ideas on how to speed this up? I can't do ImageEntity.ShapeEntities because then it turns into 1.2 seconds per ImageEntity.
Comment: I don't think EF contexts are thread-safe. I'm pretty sure that means you can't use them with PLINQ.
Answer: Entity framework context is not thread safe. From MSDN

The ObjectContext class is not thread safe. The integrity of data
  objects in an ObjectContext cannot be ensured in multithreaded
  scenarios.

If you are retrieving these entities for for read only purposes you can save few milliseconds by using NoTracking MergeOption
model.ShapeEntitie.MergeOption = MergeOption.NoTracking;

Otherwise implement some paging mechanism.
Comment: What does a paging mechanism mean in this context?
Comment: I've tried the NoTracking option, but it doesn't want to mix and match the MergeOptions. These table's are readonly, but some of the ones further up can be edited at any time.


Generic parameter 'S' could not be inferred

Question: So I'm trying to make a small dependency injection container using generics and protocol conformance. However i'm having some trouble compiling it.
I wonder if there is a swift expert that can tell me what the problem is.
import Foundation

protocol Service: NSObjectProtocol {
    init()
}

protocol ServicesType {
    func add<S: Service>(service: S.Type)
    func get<S: Service>() throws -> S
}

class Services: ServicesType {

    var services: [Service.Type] = []

    func add<S: Service>(service: S.Type) {
        if services.contains(where: { service -> Bool in return service == service }) { return }
        services.append(service)
    }

    func get<S: Service>() throws -> S {
        guard let first = services.first(where: { service -> Bool in return service == service }) else { throw ServicesTypeError.notFound }
        return first.init() as! S
    }
}

enum ServicesTypeError: Error {
    case notFound
}

Generic parameter 'S' could not be inferred is the error message when i try to compile the line below
let creditCardService: CreditCardServiceType = try self.services.get()

protocol CreditCardServiceType : Service {
    var cards: [CreditCard] { get }
}
class CreditCardService: CreditCardServiceType {
    internal required init() {}
    var cards: [CreditCard] = []
}

Comment: Added the rest of the code.
Comment: If I paste even the first piece of code into Playground it fails on ServicesType. Is there more?
Comment: I think I've got it @TommySadiqHinrichsen
Comment: Still not providing enough code.
Answer: It took a little modification to get this working in a Playground, but this seems to work.
If I'm right (in bold),
let creditCardService: **CreditCardServiceType** = try self.services.get()

Needs to be:
let creditCardService: **CreditCardService** = try self.services.get()

Full code:
import Foundation

protocol Service: NSObjectProtocol {
    init()
}

protocol ServicesType {
    func add<S: Service>(service: S.Type)
    func get<S: Service>() throws -> S
}

class Services: ServicesType {

    var services: [Service.Type] = []

    func add<S: Service>(service: S.Type) {
        if services.contains(where: { service -> Bool in return service == service }) { return }
        services.append(service)
    }

    func get<S: Service>() throws -> S {
        guard let first = services.first(where: { service -> Bool in return service == service }) else { throw ServicesTypeError.notFound }
        return first.init() as! S
    }
}

enum ServicesTypeError: Error {
    case notFound
}

class CreditCard {

}

protocol CreditCardServiceType : Service {
    var cards: [CreditCard] { get }
}

class CreditCardService: NSObject, CreditCardServiceType {

    required override init() {
        super.init()
    }
    var cards: [CreditCard] = []
}

let services = Services()
services.add(service: CreditCardService.self)

let creditCardService: CreditCardService = try services.get()

Comment: But i would like to hide away the implementing class for testing reason so that i can use another class with the same protocol.
Comment: That's a different question @TommySadiqHinrichsen. Let me have a think...
Comment: @TommySadiqHinrichsen When you add a service, just add it without the type. It ought to just be an implementation. When you get a service, you just need to look for a service that implements the protocol.
Comment: @TommySadiqHinrichsen Would you be happy marking this as answered (I got it to compile with reasoning). It may be worth raising a different question for the intended behaviour you're after. Thanks. And it was a fun one to solve.
Comment: Sure thing, i just need to let 2 days pass.
Answer: Ok what i ended up with is the following. Not as type safe as i wanted but good enough.
import Foundation

protocol Service: NSObjectProtocol {
    init()
}

protocol ServicesType {

    func add<S: Service>(service: S.Type) throws
    func get<S>() throws -> S

}

class Services: ServicesType {

    var services: [Service.Type] = []

    func add<S: Service>(service: S.Type) throws {
        if services.contains(where: { existing -> Bool in return existing == service }) { throw ServicesTypeError.allReadyAdded}
        services.append(service)
    }

    func get<S>() throws -> S {
        guard let first = services.first(where: { existing -> Bool in return existing is S }) else { throw ServicesTypeError.notFound }
        return first.init() as! S
    }

}

enum ServicesTypeError: Error {
    case allReadyAdded
    case notFound
}

usage:
try self.services.add(service: ProfileService.self)
let profileService: ProfileServiceType = try self.services.get()


Conducting a comparative analysis with studies that use different response measures

Question: I want to conduct a comparative analysis using bird playback studies. Unfortunately, many of these studies use different response measures (closest approach to the speaker, time spent near the speaker, latency to approach the speaker). These studies are still all measuring the same thing (i.e. intensity of bird response to playback stimuli) but go about it using different variables.
Is there a way to compare these studies although they use different response measures?
Answer: If you have different measures each with a standard error then you can proceed as usual. You might consider then doing a meta-regression using measure type as a moderator to see whether the response measures you quote are in fact different.
Comment: Sorry, I'm not too knowledgeable when it comes to this. Could you clarify what you mean by "proceed as usual." I can't really calculate effect size or anything because there isn't a second group to which I could compare response measures. I'm mostly wondering how to standardize values between the different response measures. I'm guessing there is a way to do this with standard error that I'm not aware of.
Comment: The usual method to which I was referring is to use inverse variance weighting. This is widely available in software in R and Stata as well as in stand-alone packages. I would not recommend trying to do it by hand. I am not sure about your point about not having a comparison group. There is no need for that if all you want to do is to produce a summary estimate.


Flask Restplus Swagger Not Loading Behind Nginx

Question: I have a Flask API and a Swagger UI generated with Flask Restplus. The API runs in a Docker container behind an Nginx container which serves it over HTTP.
Here is a health check endpoint which confirms the API is running:https://mobydq.net/mobydq/api/v1/health
<code>{"message":"MobyDQ API running in production mode"}
</code>
However, the Swagger which is supposed to load at the following URL does not load at all: https://mobydq.net/mobydq/api/doc
Here is the Nginx configuration:
<code>http {
    upstream api  {
      server api:5434;
    }

    upstream app {
      server app:3000;
    }

    # Server for https
    server {
      listen       443 ssl http2;
      server_name  mobydq.net;

      ssl_certificate      /etc/letsencrypt/live/mobydq.net/fullchain.pem;
      ssl_certificate_key  /etc/letsencrypt/live/mobydq.net/privkey.pem;

      # Location for MobyDQ Flask API
      location /mobydq {
        limit_req zone=default burst=20;
        proxy_pass http://api;
        proxy_redirect   off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
      }

      # Location for MobyDQ Web App
      location / {
        limit_req zone=default burst=20;
        proxy_pass http://app;
        proxy_redirect   off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
      }
    }

    # Default server to redirect http requests to https
    server {
      listen 80 default_server;
      server_name mobydq.net;
      listen [::]:80 default_server;

        location ~ /.well-known {
            root /var/www/letsencrypt;
        }
        location / {
            return 301 https://$host$request_uri;
        }
    }
}
</code>
Any idea why the Swagger is not loading? I looked into the http requests sent when loading the page but it did not help much. I can only see the favicon loading:

I also looked at the console and saw an error but I'm not able to tell what it means:
Comment: How did you installed swaggerUI ?
Comment: @Ciastopiekarz it is generated automatically from the Flask code thanks to a python package called Flask Restplus https://flask-restplus.readthedocs.io
Comment: it is not getting generated for me see my post : https://stackoverflow.com/q/53934180/3311276
Answer: The problem was that Nginx did not properly redirect the http requests when trying to get the resources from Swagger (the JSON configuration file in particular).
The issue has been fixed by changing the Nginx configuration as follow:
<code>[...]
  # Location for MobyDQ Flask API
  location ~ ^/(mobydq|swaggerui) {
    limit_req zone=default burst=20;
    proxy_pass http://api;
    proxy_redirect   off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
[...]
</code>
Comment: This has been a tremendous help, thank you so much


Autocomplete field not using Entity Reference list settings

Question: I'm using an Entity Reference field set to Views: Filter by an entity reference view. That works. I can choose my view: maps_by_project_season – Entity Reference.
I've chosen 3 fields in the view, and added them all to Format: Entity Reference list via settings, and I see all 3, separated by -, in the preview.
But not in the autocomplete field. That only shows the title. What am I missing?
Comment: This is a known bug in Drupal 8, see: [View output is not used for autocomplete display](https://www.drupal.org/node/2174633) you could try the patch in #76.
Comment: Thanks! Would you like to move your comment to an answer so I can flag it as correct? Also – 3 years since the original posting there?!
Answer: This is a known bug in Drupal 8, see: View output is not used for autocomplete display you could try the patch in #76
There was also another disccusion about the same thing here Views Filter by an entity reference view not working as expected, before it was closed as duplicate.


Querying for output address using regex and tx time range

Question: qqqqqqqqqqqqqqqqqqqqqqqqqqqqqu08dsyxz98whc is one out of possibly many tx which have whc substring in output address,
https://blockchair.com/bitcoin-cash/transaction/ce4b6388c3b57dc188bfafde87d7af28ee3ba210d0a3223a3bc86f6083337459
I would like to find such outputs for 2018-08 using bitdb query lang similar to mongodb,
{
  "v": 3,
  "q": {
    "find": {
      "out.e.a": { "$regex": "whc$" },
      "blk.t": {
        "$gte": "2018-08-01T00:00:00Z",
        "$lte": "2018-08-31T00:00:00Z"
      }
    },
    "limit": 1
  }
}

Unfortunately I'm not getting any result for such query
Is there some syntax issue which prevents correct results?
Comment: This seems `bitdb` specific ( noting that you just created the tag for this question ). I suspect at a glance though that the "dates" might be the issue here, and I don't see any example in the documentation showing date based queries. Possibly related to BSON Dates vs "strings", so showing a sample document ( or truncated to the relevant fields and data at least ) would actually gain you a wider audience
Answer: Try to query using Unix timestamps instead of ISO Dates.
To convert from ISO Date to unix timestamp in javascript you can do:
var myDate = new Date(ISODate("2015-10-25T00:00:00.000Z"));
var myTimeStamp = myDate.getTime() / 1000;


Defining a Plane with Two Parallel Lines

Question: I'm learning about planes in linear algebra, and my professor said that to define a plane two lines must intersect. However, I was thinking, what if the two lines are parallel? In that case, they would never intersect.
Can't two parallel lines still define a plane, you can think of the plane as a piece of paper and if I draw 2 parallel lines on it I have a plane. How can we define a plane with two parallel lines mathematically or do I must have a point of intersection?
Comment: Strictly, I think you'd also need to specify that the two lines are _distinct_; two identical lines intersect at every point, but don't define a unique plane.
Comment: Yes, they can.  Parallel lines are defined as two lines on the same plane that never intersect, and only one distinct plane contains both of those lines.  (I assume you're working with Euclidean Geometry.)
Comment: Parallel lines intersect at $\infty$
Comment: @Nate -- You say _"only one distinct plane contains both of those lines"_ while I say **two planes**. Why? A plane has two sides, a back and a front side, just like a coin. In contrast to coins you can't simply flip planes. Which of the two possible planes you have, you only see if you take a closer look, which side you're facing.
Comment: @m-stgt I think that's non-standard terminology, isn't it?  AIUI, in standard usage, planes are not oriented.  (People are welcome to define and use terms however they want, of course — but it's likely to cause confusion if they use non-standard ones without specifying.)
Comment: @gidds -- You are right with regard to the question of OP. But when playing with flat shapes/objects defining them by complanar points you may trigger colour or visibility according the side you're facing (virtually).
Comment: @m-stgt a plane is a single mathematical object, even if it is considered to have two sides.  Just like a coin is a distinct piece of currency, even though it has two sides.
Comment: @Nate -- I'm not convinced. You may flip a plane like a coin, at first glance yes. In contrast, regarding a flat object $L$-shaped with differing obverse and reverse sides, you can't convert it to its mirrored "complement" only by rotation and/or translation. That is why I am actually undecided if also planes with differing sides shouldn't be taken as two different gizmos.
Comment: @m-stgt It's a single plane containing a single set of points, regardless of which side it's viewed from.
Answer: Let the first line be $a_0 + tv$ and let the second line be $a_1 + tv$ where $t$ is a parameters.
Then your plane contain the third line $a_0+s(a_1-a_0)$ where $s$ is a parameter.
Now you have found two non-parallel lines (first line and third line) and they intersect at $a_0$. you can proceed to work on it as usual.
Answer: A plane can be defined like this
$$
E: \vec{x}=\vec{p}+r\vec{a_1}+t\vec{a_2}.
$$
Here, every point $x$ can be reached via a vector $\vec{p}$ that goes from the origin to any point $P$ on the plane. Now $r,s$ are parameters (from $\mathbb R$ if you will) and the other two vectors expand the plane. They cannot be collinear (linearly dependent) or else we will get a line.
Now imagine two lines that are parallel. The first vector $\vec{a_1}$ that we can set for the plane is the vector that we get from the first line
$$
L_1: \vec{x}=\vec{q}+r\vec{u}.
$$
So just set $\vec{a_1}=\vec{u}$. Now we need a second vector $\vec{a_2}$ but if we take the vector $\vec{v}$ from the second line
$$
L_2: \vec{x}=\vec{h}+k\vec{v}.
$$
then we cannot get a plane, as
$$
\vec{v}=b\cdot\vec{u}
$$
for some $b$.
But we can take another clever vector, a vector that goes from the first line to the second line, for example $\vec{h}-\vec{q}$.
That vector will be collinear to our first vector that generates the plane and both lines will lie in it. Very simple.


Interpreting log likelihood

Question: I have difficulty interpreting some results. I am doing an hierarhical related regression with ecoreg. If I enter the code I receive output with oddsratio's, confidence ratio's and a 2x maximized log likelihood.
However, I do not fully understand how to interpreted the 2x maximized log likelihood. As far as I know log likelihood is used as a convenient way to calculate a likelihood and it calculates the value of the parameters based on the outcomes. But I do not understand if a higher or lower value is better. I looked at several online sources e.g. https://stackoverflow.com/questions/2343093/what-is-log-likelihood, but I am still stuck.
Below the outcome I receive:
Call:
eco(formula = cbind(y, N) ~ deprivation + meanIncome, binary = ~fracSmoke +
    soclass, data = dfAggPlus, cross = cross)
Aggregate-level odds ratios:
                   OR        l95        u95
(Intercept) 0.0510475 0.03837276 0.06790878
deprivation 0.9859936 0.88421991 1.09948134
meanIncome  1.0689951 0.95574925 1.19565924
Individual-level odds ratios:
                OR       l95      u95
fracSmoke 3.124053 2.0761956 4.700765
soclass   1.001050 0.9930815 1.009083
-2 x log-likelihood:  237.4882
So, how should I interpreted a value of 237.4882 compared to an outcome of 206 or 1083? Help is much appreciated!
Comment: Wrong site for the question. You'd better try Cross Validated.
Comment: It was a cross-post of of [Interpreting log likelihood](http://stats.stackexchange.com/questions/214556/interpreting-log-likelihood)
Answer: A higher value of likelihood or log-likelihood (since log is an increasing function) is better, since it says that the parameters are more likely given the observation/data.
I suggest the wiki article on maximum likelihood estimation for further reference. (https://en.wikipedia.org/wiki/Maximum_likelihood)

Interpreting log likelihood


how to redirect on the requested scheme (http or https)

Question: I'm redirecting to some domain based on an acl condition but I want the user to end up on either http or https depending on the scheme/protocol of their request. I've managed to do that with the 2 lines shown bellow, but I'd like to convert them to just 1 line:
http-request redirect code 301 location http://www.example.com%[url] if acl_whatever !{ ssl_fc }
http-request redirect code 301 location https://www.example.com%[url] if acl_whatever { ssl_fc }

Ideally I'd like to redirect to something like %[scheme]://www.example.com%[url] but %[scheme] does not exist.
Is there a variable or function which can return http or https so I do not have to repeat the rule twice? Maybe by somehow setting a variable containing the scheme or maybe by using the value of %[ssl_fc] which is 0 or 1?
Answer: You can do this using http-request set-var and %[var(name)]:
http-request set-var(req.scheme) str(https) if { ssl_fc }
http-request set-var(req.scheme) str(http) if ! { ssl_fc }
http-request redirect code 301 location %[var(req.scheme)]://www.example.com%[url] if acl_whatever

Answer: As an addition:
If the request schema is needed in the response, txn scope must be used instead of req.
For example:
frontend http_awesome_frontend

http-request set-var(txn.scheme) str(https) if { ssl_fc }
http-request set-var(txn.scheme) str(http) if !{ ssl_fc }

# Outer frontend response:

http-response add-header X-Original-Proto %[var(txn.scheme)]

All variables are scoped, meaning they can only be accessed within the same or larger scope. When you set a variable, you prefix its names with a scope. The scope can be any of the following:

proc: variable is available during all phases
sess: variable is available during a client's entire TCP session
txn: variable is available during an entire HTTP request-response transaction
req: variable is available during the HTTP request phase only
res: variable is available during the HTTP response phase only

Sources: HA Proxy Documentation


How do I create a table in mySQL workbench?

Question: Below in the SQL I wrote in mySQL workbench it creates the database fine but will not create the table to hold my products.
DROP DATABASE bamazon_db;
CREATE DATABASE bamazon_db;
USE bamazon_db;
CREATE TABLE products (
item_id(10) AUTO INCREMENT,
product_name,
price,
stock_quantity,
);

Comment: Why You write sql query when MySQL Workbench has forms for it? About query: You've to define field types since db does not understand what kind of field You want to create.
Comment: You can also drop `USE bamazon_db;` when you fully qualified the table name with a database name like so `CREATE TABLE  bamazon_db.products (...)` that also works with SELECT, UPDATE and DELETE the same way.
Answer: You're missing the column types:
CREATE TABLE products (
    item_id INT AUTO INCREMENT,
    product_name VARCHAR(100),
    price INT,
    stock_quantity INT
);

Answer: There are two major problems with your CREATE TABLE statement:

None of your columns have types. You must declare a type for each column in the table, e.g. price DECIMAL(5,2).
You have misspelled AUTO_INCREMENT as AUTO INCREMENT.


test filenames for regex patterns in bash

Question: I'm not sure exactly how the code should be written but I want to test a file/folder for naming patterns, something like:

if [ -d $i ] && [ regex([0-9].,$i) {
       do something
    }

I want it to check if the file/folder is a directory and that the name of it is a number (i.e. 1 or 101 or 10007)...
Answer: [ cannot do regular expressions. However, [[ can:
if [[ -d $i -a $i =~ ^[0-9]+$ ]] ; then
  ...
fi

Answer: If you're using Bash earlier than version 3.2, the regex match operator =~ either doesn't exist, works differently or has bugs. You can use this glob expansion form in that case (or if you're using a POSIX shell that doesn't have it).
case $i in
    *[^0-9]*)
        do_not_a_number_stuff
        ;;
     *)
        if [ -d "$i" ]
        then
            do_something
        fi
        ;;
 esac


Predicting binary outcome when predictor variable increases

Question: Suppose I have a simple dataset of numerous observations, each with a continuous numerical variable $x$ and a binary numerical variable $y$ (with values 0 for unsatisfactory, 1 for satisfactory).
How can I predict how many of many of my observations would satisfy $y=1$ when the average $x$ in my dataset increases, say by 50%?
I was thinking of starting with a logistic regression model, but I'm not sure how to proceed.
Any guidance would be much appreciated.
Comment: Hi @ezrarusk, what do you mean by "I'm not sure how to proceed?". Are you using a specific software/language (R, Pythom, SAS)?
Comment: @lulufofo I'm using R
Answer: You can fit a model and use it to predict the probability of any given instance to be $1$, conditional on your predictor value.
As you write, one possible model is a logistic regression.
Note that the effect of increasing the predictor by 50%, or by any other increment, will depend on what you increase the value from. Here is some R code that illustrates this (note the type="response" part in the predict()s that ensure we gat probability predictions):
set.seed(1)
xx <- runif(100)
prob <- 1/(1+exp(-(xx+0.5)^2-2*(xx-0.5)))
obs <- runif(length(xx))<prob

model <- glm(obs~xx,family="binomial")

xx_plot <- seq(min(xx),max(xx),by=0.01)
plot(xx,obs,pch=19)
lines(xx_plot,
    predict(model,newdata=data.frame(xx=xx_plot),type="response"),
    col="red")

predict(model,newdata=data.frame(xx=c(0.6,0.9)),type="response")
# 0.7800048 0.9282456
predict(model,newdata=data.frame(xx=c(0.2,0.3)),type="response")
# 0.3869597 0.4928357

If you can now assume that your instances are independent, you can calculate the expected number of $y=1$ for each predictor value. Or use the binomial distribution to get a handle on the entire distribution of the number of $1$s for a constant predictor value, or possibly generalizations of the binomial for different probabilities coming from different predictor values.


What will be the coefficients in expansion of $(1+x)^n$ if $x^k =1$ for some $k<n$

Question: What will be the coefficients in expansion of $(1+x)^n$ if $x^k =1$ for some $k<n$?
Is there any faster method of finding the coefficients instead of finding the binomial coefficients and adding the respective values?
Also mention if the same can be found mod some other value.
Comment: https://en.m.wikipedia.org/wiki/Binomial_series this will help. And the additional statement probably states that $n>0$. But this series is a general one. And yeah. Use Latex.
Answer: Have you looked at Pascal's triangle? Each row is the coefficients of a binomial expansion. This is a simple way of finding the the coefficients of $(1+x)^n$ for small $n$. Also the sum of the nth row is $2^n$.
Comment: @anubhavjha does this answer your question?