text:
Q: Draw cubes with random colors using OpenGL I want every cube to have a random color but with this code the colors keep changing all the time
int espacioX = -500;
int espacioY = -500;
for(int i=1; i<=100; i++){
    for(int j=1; j<=100; j++){
        randomR = (double)rand() / (RAND_MAX);
        randomG = (double)rand() / (RAND_MAX);
        randomB = (double)rand() / (RAND_MAX);
        glColor3f(randomR,randomG,randomB);
        glTranslatef(espacioX,espacioY,0);
        glutSolidCube(9);
        glTranslatef(-espacioX,-espacioY,0);
        espacioX+=10;
    }
    glTranslatef(-1000,0,0);
    espacioY+=10;
}

How do I make them stay in the same color while the program is running?
Edit:
This is the comple code:
#include <windows.h>

/***** OpenGL library imports. *****/
#include<gl\glut.h>                                 //basic header file for OpenGL
//#include <gl\glaux.h>                             // Header File For The Glaux Library
/***** C library imports. *****/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int ScreenWidth  = 0;
int ScreenHeight = 0;
int last_x = 0, last_y = 0,left = 1,middle = 0,right = 0;
int zoom_y = 0;
int anglex=0, angley=0, anglez=0;
int lookfrom=450;
int ang=0;

void myGlutKeyboard(unsigned char Key, int x, int y)
{
    printf("%5d\n",Key);
    glutPostRedisplay();
}

void init_GL_params()
{
    static GLfloat light_ambient[] = { .250, .250, .250, .250 };
    static GLfloat light_diffuse[] = { .250, .250, .25, .250 };
    static GLfloat light_specular[] = { .250, .250, .250, .250 };

    static GLfloat light1_diffuse[] = { .250, .250, .250, .0 };
    static GLfloat light1_specular[] = { .250, .250, .250, .0 };

    glEnable (GL_LIGHTING);
    glEnable (GL_LIGHT0);
    glEnable (GL_LIGHT1);
    glDisable (GL_TEXTURE_2D);
    glDisable (GL_TEXTURE_GEN_S);
    glDisable (GL_TEXTURE_GEN_T);
    glShadeModel (GL_FLAT);
    glEnable (GL_DEPTH_TEST);
    glDepthFunc (GL_LESS);
    glEnable (GL_CULL_FACE);
    glCullFace (GL_BACK);
    glFrontFace (GL_CCW);

    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();

    glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient);
    glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse);
    glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular);

    glLightfv(GL_LIGHT1, GL_DIFFUSE,  light1_diffuse);
    glLightfv(GL_LIGHT1, GL_SPECULAR, light1_specular);
    glLightfv (GL_LIGHT1, GL_AMBIENT, light_ambient);

    glColor3f (1.0, 1.0, 1.0);

}

void setLightPosition()
{
    static GLfloat light_position[] = { 100, 200.0, 10, 1.0 };
    static GLfloat light1_position[] = { -0.0, 300.0, 0.0, 1.0 };

    // set the light position (for some reason we have to do this in model view.
    glLightfv (GL_LIGHT0, GL_POSITION, light_position);
    glLightfv(GL_LIGHT1, GL_POSITION, light1_position);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glEnable(GL_COLOR_MATERIAL);
}

void myGlutDisplay(void)
{
    init_GL_params();

      // clear the window
    glClearColor (0,0,0,0); //Color de fondo R G B
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    setLightPosition();     //Posici{on de la fuente de luz
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective(60.0f, 1.0, 1.0f, 10000.0f);
    gluLookAt(                          //punto de vista
            0 ,100 ,lookfrom ,          // desde donde veo xyz
            0, 0, 0,                    // hacia donde veo xyz
            0,1,0 );
    glRotatef(anglex, 1.0, 0.0, 0.0);
    glRotatef(angley, 0.0, 1.0, 0.0);
    glRotatef(anglez, 0.0, 0.0, 1.0);

    //Empieza a dibujar
    int espacioX = 500;
    int espacioY = 500;
    double randomR, randomG, randomB;

    for(int i=1; i<=100; i++){
        for(int j=1; j<=100; j++){
            randomR = (double)rand() / (RAND_MAX);
            randomG = (double)rand() / (RAND_MAX);
            randomB = (double)rand() / (RAND_MAX);
            glColor3f(randomR,randomG,randomB);
            glTranslatef(espacioX,espacioY,0);
            glutSolidCube(9);
            glTranslatef(-espacioX,-espacioY,0);
            espacioX-=10;
        }
        glTranslatef(1000,0,0);
        espacioY-=10;
    }

    glFlush();                                          // Flush The GL Pipeline
    glutSwapBuffers();
}

void myGlutReshape2(int mWidth, int mHeight)
{
    ScreenWidth  = mWidth;
    ScreenHeight = mHeight;
    glViewport(0, 0, (GLsizei) ScreenWidth, (GLsizei) ScreenHeight);
    glutPostRedisplay();
}

/****************************************************************/
void myGlutIdle(void)
{
    glutPostRedisplay();
}

/***************************************************************/

void myGlutMouse(int button, int button_state, int x, int y){
  if ( (button == GLUT_LEFT_BUTTON) && (button_state == GLUT_DOWN) )
  {
    last_x = x;
    last_y = y;
    left = 1;
    middle = 0;
    right = 0;
  }
  else if ((button == GLUT_RIGHT_BUTTON) && (button_state == GLUT_DOWN) )
  {
      zoom_y = y;
      right = 1;
      left = 0;
      middle = 0;
  }
}

void myGlutMotion(int x, int y){
        if (left){
            anglex+= (float) (y - last_y);
            angley+= (float) (x - last_x);

            last_x = x;
            last_y = y;
        }
        if (right)
        {
            lookfrom += (y - zoom_y);
            zoom_y = y;
        }
}

void GlutInit(int argc, char** argv)
{
    ScreenWidth  = 700;
    ScreenHeight = 700;
    /****************************************/
    /*   Initialize GLUT and create window  */
    /****************************************/
    glutInit(&argc, argv);

    glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_STENCIL );   //set up the display as a double buffer using RGB values
    glutInitWindowPosition(90, 50);                 //set the position of where you want the window to open
    glutInitWindowSize(ScreenWidth, ScreenHeight);  //set how big you want the initial window to be
    glutCreateWindow("Testing Virtual Environment" );   //what do you want the window to be called (titlebar text)

    //register callbacks
    glutDisplayFunc(myGlutDisplay);         //Register the display callback
    glutReshapeFunc(myGlutReshape2);        // -- Resize handler
    glutKeyboardFunc(myGlutKeyboard);       // -- Keyboard handler
    glutMouseFunc(myGlutMouse);             // -- Mouse Click handler
    glutMotionFunc(myGlutMotion);           // -- Mous motion handler
    glutIdleFunc(myGlutIdle);               // -- Idle handler

  glFlush();
}

int main( int argc, char **argv )
{
    GlutInit(argc, argv);
    glutMainLoop();
    return 0;
}

It was a sample code so I just posted the part that I edited, sorry. When I did a cube or a sphere with an specific color it always stayed the same so i didn't realiza that this refresh the image all the time. I don't really understand the whole thing so I don't know where it's refreshing the image.

A: It seems like you are running this code inside another loop which means you are calculating your random variables every time the scene is redrawn, this would cause the colors to change and the obvious solution would be to poulate your list of cubes once and then iterate through the list drawing the cubes on each scene refresh.
However, without seeing the rest of your code it is unclear.  Please include more information so we can give you a better answer.

A: Why not set SEED to some constant value at start of myGlutDisplay(void). That will give you the same random values each frame without any big change in your code for example like this:
void myGlutDisplay(void)
{
    init_GL_params();

      // clear the window
    glClearColor (0,0,0,0); //Color de fondo R G B
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    setLightPosition();     //Posici{on de la fuente de luz
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective(60.0f, 1.0, 1.0f, 10000.0f);
    gluLookAt(                          //punto de vista
            0 ,100 ,lookfrom ,          // desde donde veo xyz
            0, 0, 0,                    // hacia donde veo xyz
            0,1,0 );
    glRotatef(anglex, 1.0, 0.0, 0.0);
    glRotatef(angley, 0.0, 1.0, 0.0);
    glRotatef(anglez, 0.0, 0.0, 1.0);

    //Empieza a dibujar
    int espacioX = 500;
    int espacioY = 500;
    double randomR, randomG, randomB;

    srand(0x98765432); // this is the SEED

    for(int i=1; i<=100; i++){
        for(int j=1; j<=100; j++){
            randomR = (double)rand() / (RAND_MAX);
            randomG = (double)rand() / (RAND_MAX);
            randomB = (double)rand() / (RAND_MAX);
            glColor3f(randomR,randomG,randomB);
            glTranslatef(espacioX,espacioY,0);
            glutSolidCube(9);
            glTranslatef(-espacioX,-espacioY,0);
            espacioX-=10;
        }
        glTranslatef(1000,0,0);
        espacioY-=10;
    }

    glFlush();                                          // Flush The GL Pipeline
    glutSwapBuffers();
}

The value of the SEED will give you the pattern. So changing the constant will change the colors. Beware wrong constant (like 0) can corrupt the randomness of the rand() function.


text:
Q: R: can't add row to a dataframe from within a function I have a function where I want it to add its result to a dataframe. However, this doesn't seem to work. If I try the following:
testdf <- data.frame(matrix(ncol = 1, nrow = 0))
testfunction <- function() {
     testdf[nrow(testdf) + 1,] <- list("a")
}
testfunction()
testdf

[1] matrix.ncol...1..nrow...0.
<0 rows> (or 0-length row.names)

It doesn't add a row. But if I do what's in the testfunction() directly, it works:
testdf[nrow(testdf) + 1,] <- list("a")
testdf

matrix.ncol...1..nrow...0.
1                          a

Why is this the case and how can I add a row of data to a dataframe from within a function?

A: Perhaps the best way to do this would be to pass your data frame to the function as a parameter, and then to return the modified data frame to the caller.
testfunction <- function(df) {
    df[nrow(df) + 1,] <- list("a")
    return(df)
}

testdf <- data.frame(matrix(ncol = 1, nrow = 0))
testdf <- testfunction(testdf)
testdf

You could also keep everything the same but use the global assignment operator <<-:
testfunction <- function() {
    testdf[nrow(testdf) + 1,] <<- list("a")    # generally bad
}

But there are potential caveats with doing this, and the first option I gave is preferable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set UIScrollView's background image as a stretchable image? I want to set UIScrollView's background image as a stretchable image. I tried:
UIImage* backgroundImage =[[UIImage imageNamed:@"background"]
                               resizableImageWithCapInsets:UIEdgeInsetsMake(100, 0, 0, 0) ];
self.scrollView.backgroundColor = [UIColor colorWithPatternImage:backgroundImage];

But it is not stretching.
What can I do?

A: If you want to take advantage of the resizable properties of the UIImage, you need to use an UIImageView. As you've noticed, it doesn't work if you set it as a background color. Just create an UIImageView and put it behind your UIScrollView with the same frame if it has to be fixed, or inside your UIScrollView with the same size as the contentSize if you want it to scroll...

A: Add image in UIImageView and in your case set
yourImageView.contentMode = UIViewContentModeScaleAspectFill;

you can set it to any of the following
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit,
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight

Ans add This UIImageView in you scrolView.
Another way is you can use following method for get/create image size as you want.
Use following method with specific hight and width with image
+ (UIImage*)resizeImage:(UIImage*)image withWidth:(int)width withHeight:(int)height
{
    CGSize newSize = CGSizeMake(width, height);
    float widthRatio = newSize.width/image.size.width;
    float heightRatio = newSize.height/image.size.height;

    if(widthRatio > heightRatio)
    {
        newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
    }
    else
    {
        newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
    }

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

This method return NewImage, with specific size that you specify.

A: Try this one
UIImage* backgroundImage =[[UIImage imageNamed:@"back.jpg"]
                           resizableImageWithCapInsets:UIEdgeInsetsMake(100, 0, 0, 0) ];
UIGraphicsBeginImageContextWithOptions(self.scrollView.bounds.size, NO, 0.0);
[backgroundImage drawInRect:self.scrollView.bounds];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.scrollView.backgroundColor = [UIColor colorWithPatternImage:newImage];


text:
Q: Watch a sexpr for edits I'd like to tell Emacs to 'watch' a particular form (identified by its car) within a buffer and evaluate it whenever I edit it.
One approach I can think of is to add a function to post-self-insert-hook, which would find and parse the targeted form and compare it with its previously stored state.
It doesn't sound too inefficient, especially if a 'calls per second' maximum is enforced (e.g. using current-time).
Is there is a higher level / more idiomatic way to accomplish this? It sounds like the sort of problem that has been solved already.

A: I think the most natural way is to create an overlay that would span from the beginning to the end of the form.
Overlays have a modification-hooks property, and you can add a watcher function to it.
The overlay will contract or expand appropriately if you modify buffer contents strictly inside it, but you'll need to decide what to do when buffer is edited at the edges of the form. See insert-in-front-hooks, insert-behind-hooks and the last two arguments to make-overlay. I'd probably just re-create the overlay in most of these cases, just to be sure about the new bounds.
About the "calls per second" thing, you can use run-with-idle-timer.

A: Part of what @Dmitry mentioned can be turn into simple prototype. Mark (message "text") and run M-xeval-on-modify-add
(defun eval-on-modify-add ()
  (interactive)
  (let ((ov (make-overlay (region-beginning) (region-end))))
    (overlay-put ov 'modification-hooks '(eval-on-modify-execute))))

(defun eval-on-modify-execute (ov &optional flag &rest rv)
  (if flag
      (eval-region (overlay-start ov) (overlay-end ov))))

(message "test")


text:
Q: $\mathbb{Q}$ is closed in itself It is known that every space is both open and closed in itself. If the space is a metric vector space, then being closed is equivalent that every sequence that converges, converges to a point in the space.
For example, $\mathbb{Q}$ is closed in itself. What does it say about the sequence of rational approximations of some irrational number? Does it not converge? It is a Cauchy sequence so how can we say it does not converge?

A: I think you are mixing two concpets:
Yes, $\mathbb Q$ is a "closed set", since $(\Omega, \mathscr T)$ as a topological space by its own is always defined as open and closed, or we sometimes call it clopen.
But at the same time, we call a space "complete" if every Cauchy sequence converges within the space - and in this case, $\mathbb Q$ is not complete.

A: $(\mathbb{Q},|.|)$ is closed in itself.
But a sequence of $q_n$ rational numbers which converges to an irrational $r$, does not converge in $\mathbb{Q}$
It is a Cauchy sequence but does not converge in $(\mathbb{Q},|.|)$
Thus we can say that $\mathbb{Q}$ with the subspace topology inherited from the usual topology of $\mathbb{R}$ is not a complete space.
Take for instance $x_n=(1+1/n)^n \rightarrow e$.
Thus $x_n$ is a Cauchy sequence but $e \notin \mathbb{Q}$

A: If $A$ is a subset of a topological space $X$, then "$A$ is closed (in $X$)" implies that if a sequence of points of $A$ converges to a point in $X$, then the limit is itself in $A$.
This doesn't say anything about the possibility of converging to points outside $X$ -- indeed, the topology on $X$ that declares $A$ to be closed does not even know whether such points exist or what it would mean to converge towards them.

What does it say about the sequence of rational approximations of some irrational number? Does it not converge? It is a Cauchy sequence so how can we say it does not converge?

It doesn't converge in $\mathbb Q$ because there is no point in the topological space that it converges to. Some metric spaces have the property that all Cauchy sequences converge (they're called complete), but $\mathbb Q$ is not one of them.

A: The "Cauchy criterion" does NOT hold in the rational numbers.  There are, as you say, "Cauchy" sequences of rational numbers that do not converge to a rational number.
That is, in fact, one way of "constructing" the real number system:  We say that two Cauchy sequences of rational numbers are "equivalent" if and only if their "difference" (if the sequences are $\{a_n\}$ and $\{b_n\}$ then their "difference" is the sequence $\{a_n- b_n\}$.)  converges to 0.  We then identify the equivalence classes with the real numbers.  It is easy to show that if two Cauchy sequences of rational number converge to the same rational number then they are equivalent in this sense and that any other such sequence that is equivalent converges to the same rational number.  We identify that equivalence class with that rational number so that, in this sense, the set of rational number is a subset of the set of real number.  But since there exist Cauchy sequences that do not converge to a rational number, the corresponding equivalence classes give us the irrational numbers.

A: The equivalence statement you stated in the first paragraph is more tricky than it appears! Note that the necessary and sufficient condition you stated is equivalent to that the set equals its closure. However, when we say $\mathbb{Q}$ is closed in itself, we are certainly not saying $\mathbb{Q}$ is its closure that is usually taken to be $\mathbb{R}$ for granted unless otherwise declared. You probably are having trouble with the "inconsistency" of these pieces of information. The crux is this. We say $\mathbb{Q}$ is closed in itself because $\mathbb{Q}^{c} = \varnothing$ is open by definition. But note that here $\mathbb{Q}^{c}$ is the complement of $\mathbb{Q}$ with respect to $\mathbb{Q}$. So, when $\mathbb{Q}$ itself is considered the ambient space, the closure of $\mathbb{Q}$, which is by definition (if you are not using this definition, never mind; they are equivalent.) the intersection of all closed sets that includes $\mathbb{Q}$, is $\mathbb{Q}$ itself. So, if you go through the proof of the equivalence theorem again, then you will see why the "contradiction" resolves.


text:
Q: Is there a good way to parse sql case statement? The goal is to parse the sql statement in Python, and I have some difficulties using sqlparse to parse the case statement. I have tried the method in this link Parse CASE WHEN statements with sqlparse, but the result becomes messy when the data set becomes large. For example, if the case statement is like:
CASE
           WHEN ticket.status IN ('new',
                                  'assigned')
                AND ticket_custom.ticket = 3 THEN "Win"

the parsed result is shown as below:
([<Keyword 'WHEN' at 0x1870AFBA6A8>, <Whitespace ' ' at 0x1870AFBA708>, <Comparison 'ticket...' at 0x1870AFF55C8>, <Newline ' ' at 0x1870AFBC8E8>, <Whitespace ' ' at 0x1870AFBC948>, <Whitespace ' ' at 0x1870AFBC9A8>, <Whitespace ' '
at 0x1870AFBCA08>, <Whitespace ' ' at 0x1870AFBCA68>, <Whitespace ' ' at 0x1870AFBCAC8>, <Whitespace ' ' at 0x1870AFBCB28>, <Whitespace ' ' at 0x1870AFBCB88>, <Whitespace ' ' at 0x1870AFBCBE8>, <Whitespace ' ' at 0x1870AFBCC48>, <Whitespace ' ' at 0x1870AFBCCA8>,
<Whitespace ' ' at 0x1870AFBCD08>, <Whitespace ' ' at 0x1870AFBCD68>, <Whitespace ' ' at 0x1870AFBCDC8>, <Whitespace ' ' at 0x1870AFBCE28>, <Whitespace ' ' at 0x1870AFBCE88>, <Whitespace ' ' at 0x1870AFBCEE8>, <Keyword 'AND' at 0x1870AFBCF48>, <Whitespace ' ' at 0x1870AFBCFA8>, <Comparison 'ticket...' at 0x1870AFF5648>, <Whitespace ' ' at 0x1870AFBD2E8>], [<Keyword 'THEN' at 0x1870AFBD348>, <Whitespace ' ' at 0x1870AFBD3A8>, <Error '"' at 0x1870AFBD408>, <Identifier 'Win' at 0x1870AFEF048>, <Error '"' at 0x1870AFBD4C8>, <Newline ' ' at 0x1870AFBD528>, <Whitespace ' ' at 0x1870AFBD588>, <Whitespace ' ' at 0x1870AFBD5E8>, <Whitespace ' ' at 0x1870AFBD648>, <Whitespace ' ' at 0x1870AFBD6A8>, <Whitespace ' ' at 0x1870AFBD708>, <Whitespace ' ' at 0x1870AFBD768>, <Whitespace ' ' at 0x1870AFBD7C8>, <Whitespace ' ' at 0x1870AFBD828>, <Whitespace ' ' at 0x1870AFBD888>, <Whitespace ' ' at 0x1870AFBD8E8>, <Whitespace ' '
at 0x1870AFBD948>]),

You can imagine what the result would become when the sql statement becomes complex.
And the result I would like to have is actually similiar to the way that sql_metadata parse the subqueries:
{'case statement name':"case statement content" }

the sql_metadata and sqlparse could parse subqueries like this but not for the case statement, is there any other way to do that in Python?
Here is the complex example:
SELECT '%c%' AS Chapter =
    CASE
           WHEN ticket.status IN ('new',
                                  'assigned')
                AND ticket_custom.ticket = 3 THEN "Win"
           WHEN ticket.status IN ('new',
                                  'assigned')
                AND ticket_custom.ticket = 2 THEN "Lose"
           WHEN ticket.status IN ('new',
                                  'assigned')
                AND ticket_custom.ticket = 1 THEN "Draw"
           WHEN ticket.status IN ('new',
                                  'assigned')
                AND EmployeeConsolidated.id= 49887 THEN "Undefined"
       END AS Feature,
       ticket_custom.ticket,
       ticket_custom.mn,
       ticket_custom.value,
       ticket_custom.category,
       SUM(CASE
               WHEN ticket.status IN ('new', 'assigned') THEN 1
               ELSE 0
           END) AS NEW,
       SUM(CASE
               WHEN ticket.status IN ('new', 'assigned') THEN 1
               ELSE 0
           END) AS OLD,
       SUM(CASE
               WHEN ticket.status='closed' THEN 1
               ELSE 0
           END) AS 'Closed',
       count(id) AS Total,
       EmployeeConsolidated.id,
       EmployeeConsolidated.rate,
       ticket.id AS _id
FROM engine.ticket
INNER JOIN engine.ticket_custom ON ticket.id = ticket_custom.ticket
LEFT JOIN
  (SELECT e.employee_id AS "Employee #" ,
          e.first_name || ' ' || e.last_name AS "Name" ,
          e.email AS "Email" ,
          e.phone_number AS "Phone" ,
          TO_CHAR(e.hire_date, 'MM/DD/YYYY') AS "Hire Date" ,
          TO_CHAR(e.salary, 'L99G999D99', 'NLS_NUMERIC_CHARACTERS = ''.,'' NLS_CURRENCY = ''$''') AS "Salary" ,
          e.commission_pct AS "Comission %" ,
          'works as ' || j.job_title || ' in ' || d.department_name || ' department (manager: ' || dm.first_name || ' ' || dm.last_name || ') and immediate supervisor: ' || m.first_name || ' ' || m.last_name AS "Current Job" ,
          TO_CHAR(j.min_salary, 'L99G999D99', 'NLS_NUMERIC_CHARACTERS = ''.,'' NLS_CURRENCY = ''$''') || ' - ' || TO_CHAR(j.max_salary, 'L99G999D99', 'NLS_NUMERIC_CHARACTERS = ''.,'' NLS_CURRENCY = ''$''') AS "Current Salary" ,
          l.street_address || ', ' || l.postal_code || ', ' || l.city || ', ' || l.state_province || ', ' || c.country_name || ' (' || r.region_name || ')' AS "Location" ,
          jh.job_id AS "History Job ID" ,
          'worked from ' || TO_CHAR(jh.start_date, 'MM/DD/YYYY') || ' to ' || TO_CHAR(jh.end_date, 'MM/DD/YYYY') || ' as ' || jj.job_title || ' in ' || dd.department_name || ' department' AS "History Job Title"
   FROM employees e -- to get title of current job_id

   JOIN jobs j ON e.job_id = j.job_id -- to get name of current manager_id

   LEFT JOIN employees m ON e.manager_id = m.employee_id -- to get name of current department_id

   LEFT JOIN departments d ON d.department_id = e.department_id -- to get name of manager of current department
-- (not equal to current manager and can be equal to the employee itself)

   LEFT JOIN employees dm ON d.manager_id = dm.employee_id -- to get name of location

   LEFT JOIN locations l ON d.location_id = l.location_id
   LEFT JOIN countries c ON l.country_id = c.country_id
   LEFT JOIN regions r ON c.region_id = r.region_id -- to get job history of employee

   LEFT JOIN job_history jh ON e.employee_id = jh.employee_id -- to get title of job history job_id

   LEFT JOIN jobs jj ON jj.job_id = jh.job_id -- to get namee of department from job history

   LEFT JOIN departments dd ON dd.department_id = jh.department_id
   ORDER BY e.employee_id) AS EmployeeConsolidated ON e.employee_id = engine.ide
WHERE ticket_custom.name='chapter'
  AND ticket_custom.value LIKE '%c%'
  AND TYPE='New material'
  AND milestone='1.1.12'
  AND component NOT LIKE 'internal_engine'
GROUP BY ticket.id

The desired output should be like this:
{'Feature':"Case When ticket.status IN ('new','assigned') and ticket_custom.ticket = 3 then "Win" When  ticket.status IN ('new','assigned') and ticket_custom.ticket = 2 then "Lose" When ticket.status IN  ('new','assigned') and ticket_custom.ticket = 1 then "Draw" When ticket.status IN   ('new','assigned') and EmployeeConsolidated.id= 49887 then "Undefined" End as Feature," },
{'New':"SUM(CASE WHEN ticket.status IN ('new','assigned') THEN 1 ELSE 0 END) as New," },
{'Old':"SUM(CASE WHEN ticket.status IN ('new','assigned') THEN 1 ELSE 0 END) as Old," },
.......

A: You can use SQLGlot to parse your query and iterate or find different expression types.
Parsing your original example yields an AST.
(CASE ifs:
  (IF this:
    (AND this:
      (IN this:
        (COLUMN this:
          (IDENTIFIER this: status, quoted: False), table:
          (IDENTIFIER this: ticket, quoted: False)), expressions:
        (LITERAL this: new, is_string: True),
        (LITERAL this: assigned, is_string: True)), expression:
      (EQ this:
        (COLUMN this:
          (IDENTIFIER this: ticket, quoted: False), table:
          (IDENTIFIER this: ticket_custom, quoted: False)), expression:
        (LITERAL this: 3, is_string: False))), true:
    (LITERAL this: Win, is_string: True)))


text:
Q: Extract data from Wikidata using PHP I have used Faker to generate persons and I want to do the same thing using Wikidata. By getting names, date of birth, gender, first paragraph and other specified similar data. In addition being able to avoid duplicates by checking existing persons (e.g Q4926) I have fetched before. Wikidata Query = https://w.wiki/5LUr
Is it possible to use freearhey/wikidata or addwiki/wikibase-api or should query.wikidata.org/sparql be used diretly
Code snippet currently used
if ($s == 'generate_fake_users') {
    require "assets/libraries/fake-users/vendor/autoload.php";
    $faker = Faker\Factory::create();
    if (empty($_POST['password'])) {
        $_POST['password'] = '123456789';
    }
    $count_users = $_POST['count_users'];
    $password = $_POST['password'];
    $avatar = $_POST['avatar'];
    ob_end_clean();
        header("Content-Encoding: none");
        header("Connection: close");
        ignore_user_abort();
        ob_start();
        header('Content-Type: application/json');
        echo json_encode(array(
            'status' => 200
        ));
        $size = ob_get_length();
        header("Content-Length: $size");
        ob_end_flush();
        flush();
        session_write_close();
        if (is_callable('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }
    for ($i=0; $i < $count_users; $i++) {
        $genders = array_keys($wo['genders']);
        $random_keys = array_rand($genders, 1);
        $gender = array_rand(array("male", "female"), 1);
        $gender = $genders[$random_keys];
        $re_data  = array(
            'email' => Site_Secure(str_replace(".", "_", $faker->userName) . '_' . rand(111, 999) . "@domain.com", 0),
            'username' => Site_Secure($faker->userName . '_' . rand(111, 999), 0),
            'password' => Site_Secure($password, 0),
            'email_code' => Site_Secure(md5($faker->userName . '_' . rand(111, 999)), 0),
            'src' => 'Fake',
            'gender' => Site_Secure($gender),
            'lastseen' => time(),
            'active' => 1,
            'first_name' => $faker->firstName($gender),
            'last_name' => $faker->lastName
        );
        if ($avatar == 1) {
            $urls = array("http://lorempixel.com/".$wo['profile_picture_width_crop']."/".$wo['profile_picture_height_crop']."/people","https://placeimg.com/".$wo['profile_picture_width_crop']."/".$wo['profile_picture_height_crop']."/people");
            $rand = rand(0,1);
            $url = $urls[$rand];
            $a = Site_ImportImageFromFile($url,'_url_image','avatar');
            if (!empty($a)) {
                $re_data['avatar'] = $a;
            }
        }
        $add_user = Site_RegisterUser($re_data);
    }
    header("Content-type: application/json");
    echo json_encode($data);
    exit();
}


text:
Q: Android Studio Error - Could not resolve androidx.core When working offline I just began learning programming Android Apps with Kotlin in Android Studio 3.6.1 and I'm trying to work offline, so I used the instructions in this article to do so:
https://developer.android.com/studio/intro/studio-config#offline
but i still get these Errors when building a project and I cannot run the application or edit the interface of the application.

*

*ERROR: Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve androidx.appcompat:appcompat:1.1.0.

*ERROR: Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve androidx.appcompat:appcompat:1.1.0.

*ERROR: Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve androidx.core:core-ktx:1.2.0.

*ERROR: Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve androidx.appcompat:appcompat:1.1.0.

*ERROR: Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve androidx.core:core-ktx:1.2.0.

*ERROR: Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve androidx.core:core-ktx:1.2.0.

I tried some solutions here, but it seems like they had different versions than the one I'musing.
I also tried this link, but it didn't work, either.
Android Studio 3.5.2 Offline setup Error: app@debug/compileClasspath
I need to solve these issues and use Android Studio offline, so I cannot use any solution that requires being online.
Looking forward to your solutions, please.
Thanks ^^


text:
Q: What are the odds of rolling a 1 and a 20 in two d20 dice? So, one of these days a friend of mine rolled two d20 dice and got a $1$ in one of them and a $20$ in the other. I was thinking, what are the odds of this happening?

A: On a D-20 dice there are 20 possible outcomes.  The probability of rolling any particular face of the dice (assuming that it is a fair dice) is ${1}\over{20}$.  These events are independent of each other, this means that the outcomes of the dice do not influence each other.  To find a particular two dice combination we have to take the probability of the first outcome and multiply it by the probability of the second outcome.
$$\frac{1}{20} * \frac{1}{20} = \frac{1}{400}$$
The chance of rolling a one and a 20 is $\frac{1}{400}$.  This is actually the same probability as any particular combination of those two dice.  For example, rolling a 3 and a 16 would also be a $\frac{1}{400}$ probability.
Since there are two possible ways to get the combination of one and 20, first dice is one and second is 20, or first dice is 20 and second is one.  You add the two probabilities together
$$\frac{1}{400} + \frac{1}{400} = \frac{2}{400} = \frac{1}{200}$$
This is the final probability of this event.

A: Imagine the two dice are different colors.  One is blue and the other green.
There are $20$ possible options the blue die can roll.  For each of those $20$ there are $20$ possible options there green die can roll.  So there are $20*20 = 400$ possible outcomes.  Each one is equally likely.
There are $2$ ways to roll a $1$ and one and a $20$ on the other.  Either the blue die is $1$ and the green die is $20$, or the green die is $1$ and the blue die is $20$.
So out of the $400$ possible outcome $2$ of them are a $1$ and a $20$.
So the probability is $\frac 2{400} =\frac 1{200}$.
BTW.  That is "probability".  Technically "odds" is a different concept.  The odds of rolling a $1$ and a $20$ are $2$ in favor to $(400 - 2)$ against.  Or $2$ in favor to $398$ against.  Or reduced proportionally $1$ in favor to $199$ against.  Or simply, $1$ to $199$ or $1:199$.


text:
Q: SharePoint Modern Library - Power Automate notification email - 6 Months after Created date I have a basic SharePoint Online library in which I need to send a notification email 6 months (184 days) from the Created Date.  It's a reminder to an Item's submitter that they're document needs to be updated.  I think Power Automate would be the best option, but i'm not sure how to set it up.  I selected the template to send notification when an item is uploaded.  I assumed I'd create a condition based off the Created field, but I'm not sure what the next expression would be.
Thanks for your help!

A: Theoretically, if you used the triggers for when an item/file is created, you would then use a Delay action to delay for six months, and then you would send the email. This issue with this technique is that a flow run cannot last more than thirty days.
The way I would handle this task is to use a scheduled flow (i.e. a timer trigger). I would run the flow once a day and query the list/library for items created six months ago, and send email notifications for the items that were found.


text:
Q: Redirecting to WWW domain if site is opened with HTTPS I want to redirect my site to https://www.domain.com  if someone opens the site with HTTPS.
Basically, if someone opens the site with  then it should redirect to .
i DONOT want to redirect to HTTPS if a vistior opens the site with HTTP, it should work as it is.
I have tried with these codes :
RewriteCond %{SERVER_PORT} ^443$
RewriteRule .? http://www.domain.com/%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} on
RewriteRule .? http://www.domain.com/%{REQUEST_URI} [L,R=301]

But its not working. Can anyone guide me here.
Thanks

A: The question is a bit unclear. If you want to redirect from https to http://www , you can use :
RewriteCond %{SERVER_PORT} 443
RewriteRule .? http://www.domain.com%{REQUEST_URI} [L,R=301]

Or if actually want to redirect from non-www to www, you can use :
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs
RewriteRule .? http%1://www.domain.com%{REQUEST_URI} [L,R=301]


text:
Q: How to add multiple classes to an element based on props using Vue.js? First look at my code to understand the problem.
<template>

</template>

so as you can see here do i have my flat prop that will trigger a flat class to show a box-shadow or not. But i also want someone to trigger the app prop that will put some padding in the header.
the problem here is dat you can't put multiple :classes in a element.
is there any solution for this?

A: Try to combine them in the same class attribute as follows:

header

See the official documentation

A: There are several ways to achieve what you're trying to do, Vue is great at this.
1. Pass an array of classes

2. Pass an object

Here, only the props that have a truthy value will be set as classes.
2.1 If you're using ES6
You can use the object property value shorthand

Bonus
You can also mix 1 and 2 if necessary (I've needed it sometimes)

A: You can create a method that returns the same object as @Boussadjra Barhim answer.
//if value is evaluated into true, the key will be a part of the class
setClass: function(flat, app){
    return {
      flat: flat,
      app: app
    }
}

Use it via
<element :class="setClass(flat, app)" />

But in this case you can write other longer code (without uglifying the template) to process the values before returning an object
setClass: function(flat, app){
    //do something else with inputs here
    return {
      flat: flat,
      app: app
    }
}


text:
Q: Alamofire User Token Authorization Swift I have some problems with Alamofire. What I want do to:
Receiving a user token when username & password is correct. This works in my code.
What I need to do now is to send the token to retrieve data from the API.
curl -X GET -H "Authorization: Token 5f1c81fb59a7ddf3a2" http://myurl.com

This is what I have to receive the Token:
 let parameters = [
        "username" : usernameLabel.text!,
        "password" : passwordLabel.text!
    ]

    let credentialData = "\(usernameLabel.text):\(passwordLabel.text)".dataUsingEncoding(NSUTF8StringEncoding)!

    let base64Credentials = credentialData.base64EncodedStringWithOptions([])

    let headers = ["Authorization": "Basic \(base64Credentials)"]

    Alamofire.request(.POST, requestString, parameters: parameters, encoding: .JSON, headers: headers)
        .responseJSON { response in switch response.result {

        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

            let response = JSON as! NSDictionary

            //example if there is an token
            self.userToken = response.objectForKey("token") as! String?
            print("here comes the userToken \(self.userToken)")

            self.retrieveData()

            debugPrint(response)

        case .Failure(let error):
            print("Request failed with error: \(error)")

            }

Here I want to send the token for another request (retrieving JSON data)
  func retrieveData() {
    let headers = ["Authorization": "\(self.userToken)"]

    Alamofire.request(.GET, URL, encoding: .JSON, headers: headers)
        .responseJSON { response in switch response.result {

        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

            let response = JSON as! NSDictionary
            print(response)

            debugPrint(response)

        case .Failure(let error):
            print("Request failed with error: \(error)")

            }

    }

}

The answer is always:   detail = "Authentication credentials were not provided.";
but curl works :/
What is wrong with my retrieveData function?


text:
Q: Why does mutate doesn't work if we put ifelse of results of types both "character" and "numeric"? I want to create a custom column to a dataframe grouped by level which will be the mean of 2 variables. When there is a missing data, I need a sign of masking, like: "--". Example:
df <-  data.frame(level= c(1,2,3,4,5,6,7,8,8,6,7,5,4,2), var1=c(1,1,2,3,4,5,6,7,8,8,6,7,5,4), var2 = c(2,NA,1,2,3,4,5,6,7,8,8,6,7,5))

doesn't work:
df  %>%
  group_by(level) %>%
  mutate(result = ifelse(is.na(var1) | is.na(var2), "--", mean(c(var1,var2))))

doesn't work:
df %>%
  group_by(level) %>%
  mutate(result = ifelse(!(is.na(var1) | is.na(var2)), mean(c(var1,var2)), "--" ))

doesn't give an error:
df %>%
  group_by(level) %>%
  mutate(result = ifelse(is.na(var1) | is.na(var2), mean(c(var1,var2)), "--" ))

The error I get in 2 first cases is:
Error in mutate_impl(.data, dots) :
  Column `result` can't be converted from numeric to character

Can you tell me what am I missing, how does mutate work so I can actually obtain what I need?
Thanks!

A: From ifelse documentation -

ifelse(test, yes, no)
ifelse returns a vector of the same length and attributes (including
  dimensions and "class") as test and data values from the values of yes
  or no. The mode of the answer will be coerced from logical to
  accommodate first any values taken from yes and then any values taken
  from no

Basically you can't mix characters and numbers for yes/no values. It is not a good idea mix characters and numbers in the same variable anyways. Consider using NA_real_ instead of --. If you must do it your way then you can try using as.character(mean(c(var1,var2))) but now your means are returned as characters.
df  %>%
  group_by(level) %>%
  mutate(result = ifelse(is.na(var1) | is.na(var2), "--", as.character(mean(c(var1,var2)))))

# A tibble: 14 x 4
# Groups:   level [8]
   level  var1  var2 result
   <dbl> <dbl> <dbl> <chr>
 1     1     1     2 1.5
 2     2     1    NA --
 3     3     2     1 1.5
 4     4     3     2 4.25
 5     5     4     3 5
 6     6     5     4 6.25
 7     7     6     5 6.25
 8     8     7     6 7
 9     8     8     7 7
10     6     8     8 6.25
11     7     6     8 6.25
12     5     7     6 5
13     4     5     7 4.25
14     2     4     5 NA

Note -
You can use write.csv(df, "report.csv", na = "--") if you only want to replace NA with "--" in your report.

A: We can use case_when
 df %>%
   group_by(level) %>%
   mutate(result = case_when(is.na(var1)|is.na(var2) ~ "--",
                       TRUE ~ as.character(mean(c(var1, var2)))))
# A tibble: 14 x 4
# Groups:   level [8]
#   level  var1  var2 result
#   <dbl> <dbl> <dbl> <chr>
# 1     1     1     2 1.5
# 2     2     1    NA --
# 3     3     2     1 1.5
# 4     4     3     2 4.25
# 5     5     4     3 5
# 6     6     5     4 6.25
# 7     7     6     5 6.25
# 8     8     7     6 7
# 9     8     8     7 7
#10     6     8     8 6.25
#11     7     6     8 6.25
#12     5     7     6 5
#13     4     5     7 4.25
#14     2     4     5 <NA>


text:
Q: HTTP Error 404.17 - Not Found (.Net 4) I've just got a new server setup on Windows 2008 Web edition. I'm trying to set the first asp.net 4 application up on it but am having nothing but problems.
The latest is that I'm getting the 404.17 error, which says "the requested content appears to be script and will not be served by the static file handler.".
I've done a lot of research on google but most suggestions seem to be to run aspnet_regiis -i to install asp.net 4. I've done this several times both on the Framework and Framework64 folders, but with no success.
I tried changing from the default application pool to a .net4 application pool, which appeared  to work at first and I instead got a server error to do with permissions. I fixed that, and immediately the 404.17 error returned.
Other suggestions I've read say to go into the "turn windows features on and off" and make sure .net 4 is selected there under IIS. However on this server clicking "turn windows features on and off" takes me to the standard windows 2008 server manager. I click "add features" there, and only ".NET Framework 3.0 Features (Installed)" is listed and selected. .NET 4 isn't shown there, yet it is selectable through the application pools.
What else can I try to get the website running as I'm at a complete loss now. Its annoying because my old server was easy to manage - I did it all through the server itself without a control panel (Windows 2003), now on my new server I have to manage most of it through Plesk because there is no dns.
Any help would be much appreciated.

A: I too had the same problem but solved it with simple solution.   My program was in framework 4.0 but in application pool was mapped to framework 2.0.
Just changed the frame work in application pool to 4.0.
It worked.

A: I've finally figured out the problem, and it was to do with Plesk itself.
After delving through some of the thousands of links throughout the plesk control panel I found a page for "Website Scripting and Security". Under there it was set to .NET 2.0. However, even though I'd installed .NET 4 on the server, Plesk didn't know about it. Although the application pool I'd set the website to run under through IIS was .NET 4, it still wouldn't work for some reason.
I then found another page under "tools and settings" for server components, and on that page is a refresh button. Hit that and it suddenly realised that .NET 4 was installed, went back to the website scripting and security page, selected .NET 4, and hey presto, I got a server error (never have I been so glad to see a server error).
I then just had to give the application pool identity read access to the web folder, and the website worked.
I wish I'd paid an extra £15 per month for Windows 2008 Standard edition now so I could manage it all manually without Plesk.

A: Ensure that you are running this application under a Virtual Directory, also ensure that your IIS has ASP, ASP.Net, ISAPI Extensions And Filters, Static Content installed.

A: Change the .net framework from 'plesk' panel:

*

*go to Domains

*select then domain

*Go to 'Domain and Websites & Domains'

*Hide Advanced Operations

*Go to 'Asp.net Settings'

*Go to 'Change Version'

*select 4.0
If you don't have the 4.0 option then you must install the framework on your server first.


text:
Q: Getting a response status code with lua-request How is it possible to get the response status code of a request using lua-http ?
If that is not possible with it what module/library should i use ?

A: From the docs :
local http_request = require "http.request"
local headers, stream = assert(http_request.new_from_uri("http://example.com"):go())
print(headers:get ":status")


text:
Q: Is it possible to embed a scrollable frame inside a PDF? (This is an end-of-year crazy question)
Is it possible to embed a (scrollable) frame or a PDF inside a PDF? If so, how to do it in (pdf)LaTeX?
This is something pretty common in HTML (see for example http://www.echoecho.com/htmlframes01.htm). Here it is a webpage with PDF frames https://www.cs.tut.fi/~jkorpela/html/iframe-pdf.html
Here it is a fake screenshot so you get the idea.
Portable and non-portable (e.g. only-Acrobat) answers are welcomed.

Example of a down arrow below a frame. The up arrow can be on top of the frame and the triangles point up.

A: Vertical scrolling based on the animate package; definition of command \smoothScroll taken from an earlier post with slight modifications.
As an example document, we take lppl.pdf from TEXMF/doc/latex/base/lppl.pdf, the pages somewhat trimmed.
Update  with suggestions incorporated:

Start auto-scroll by clicking on the "widget", pause auto-scroll on mouse-down in the "widget" (and moving the mouse out, while keeping it pressed).
The buttons above and below the "widget" step through the document on mouse click.
[Shift]+click on the buttons rewinds to the top or jumps to the bottom of the document.

Adobe Reader required. Open on ↗ShareLaTeX.

\documentclass[a5paper]{scrartcl}

\usepackage{multido}
\usepackage{graphicx}
\usepackage{MnSymbol} % \triangle, \triangledown
\usepackage{animate}
\usepackage{media9}   % \mediabutton
\usepackage{xsavebox} % \xsbox{<xsbox id>}{<content>} , \the<xsbox id>

%%%%%%% docToBox  %%%%%%%%
\newcommand\docToBox[3]{%
  % #1 <file name (PDF)>
  % #2 <left> <bot> <right> <top> % trim pages by given amounts (PS points)
  % #3 <boxnum>
  \pdfximage{#1}%  just for counting pages
  \multido{\i=1+1}{\pdflastximagepages}{%
    \global\setbox#3=\vbox{%
      \box#3%
      \hbox to \textwidth{\includegraphics[page=\i,trim=#2,clip,width=\textwidth]{#1}}%
    }%
  }%
}
%%%%%%% /docToBox %%%%%%%%

%%%%%%% smoothScroll %%%%%
\newcommand\smoothScroll[5][]{%
  % [#1] autoplay, controls, ... (see: texdoc animate)
  % #2 <boxnum>
  % #3 <viewport height>
  % #4 <steps>
  % #5 <steps per sec> while playing; >25 doesn't make sense
  \edef\mywd{\the\wd#2}%
  \edef\myht{\the\ht#2}%
  \edef\mytht{\the\dimexpr\ht#2+\dp#2\relax}%
  \xsbox{XFormOfDoc}{\usebox{#2}}% distill box into re-usable PDF XObject
  \edef\portht{\the\dimexpr#3\relax}%
  \begin{animateinline}[#1,width=\mywd,height=\portht]{#5}%
    \multiframe{#4}{
      dRaiseLen=\the\dimexpr-\myht+\portht\relax+\the\dimexpr(\mytht-\portht)/#4\relax
    }{%
      \begin{minipage}[b][\portht][b]{\mywd}%
        \raisebox{\dRaiseLen}[0pt][0pt]{\theXFormOfDoc}%
      \end{minipage}%
    }%
  \end{animateinline}%
}
%%%%%%% /smoothScroll %%%%%

\begin{document}\Huge

\newbox\lipsumbox
%load the document with trims into save-box
\docToBox{lppl.pdf}{131 110 115 121}{\lipsumbox}
\edef\boxwidth{\the\wd\lipsumbox}%

\noindent Before you consider using \LaTeX, read the fine-print:\\
\noindent\mediabutton[
  jsaction={
    if(event.shift){anim.lppl.pause();anim.lppl.frameNum=0;}
    else try{anim.lppl.frameNum--}catch(e){}
  }
]{\fboxsep=0pt\framebox[\boxwidth][c]{\tiny\strut$\triangle\triangle\triangle$}}
%the scrolling widget
\noindent{\fboxsep=-\fboxrule\fbox{\smoothScroll[label=lppl]{\lipsumbox}{0.79\textheight}{512}{25}}}
\vskip -0.8\baselineskip
\noindent\mediabutton[
  jsaction={
    if(event.shift){anim.lppl.pause();anim.lppl.frameNum=anim.lppl.numFrames-1;}
    else try{anim.lppl.frameNum++}catch(e){}
  }
]{\fboxsep=0pt\framebox[\boxwidth][c]{\tiny\strut$\triangledown\triangledown\triangledown$}}%

\end{document}


text:
Q: JSON parse error hstore serialization rails 4 Could someone point out where the JSON error is in the following...
"{\"a\"=>\"b\"}"

I get the follow error when doing JSON.parse
JSON::ParserError: 757: unexpected token at '{"a"=>"b"}'

Thanks
UPDATE
Yep, as the commenter points out, I can't parse it bc it is a Ruby hash literal. FWIW I was dealing with this value when trying to do nested hashes inside of PG Hstore.  Turns out, you shouldn't really do that / that is not what Hstore is currently designed to support.  If you wanted to stick with this approach you can do the following to get the hash value:
eval("{\"a\"=>\"b\"}")

A: That's not JSON. If I assume the outer quotes and the escapes on the inner quotes are not really in the data, that's:
{"a"=>"b"}

JSON doesn't use =>. In JSON it would be
{"a":"b"}

Edit: Ah, @falsetru says in a comment that what you have there is a Ruby Hash literal. I'm not a Ruby guy.

A: Here is a simple answer to convert a PG Hstore string (data) into a javascript object :
JSON.parse( data.replace(/=>/g,':') )

or
JSON.parse( data.replace(/"/g,'"').replace(/=>/g,':') )


text:
Q: SQL JOIN and CASE I hope you can help me with this simple query that I've been working on for a few days. I am new to SQL and have read answers to similar questions, but did not find what I was looking for.
My goal is to query information from two different tables, and display it in a readable manner. I was successful in creating the following query, which displays all of the information I need:
SELECT
    PA.EntityName,
    PA.EntityType,
    PO.Name,
    PO.Feature
FROM PolicyAssociations PA
JOIN Policies PO ON PO.Id = PA.PolicyId
WHERE
    PA.EntityType='1'
    or
    PA.EntityType='2'
GROUP by PO.Name, PA.EntityName

Now I need to change the output of the EntityType column (displayed as 'Object Type') from numerical values to text, e.g. display the word 'Computer' instead of '1' and 'User' instead of '2'.
The following query works independently, but I have failed to incorporate these strings into the main JOIN query in many variations:
SELECT EntityType,
CASE
  WHEN EntityType = '1' THEN 'Computer'
  WHEN EntityType = '2' THEN 'User'
END
FROM policyassociations

A: This should do:
SELECT
    PA.EntityName,
    PA.EntityType,
    PO.Name,
    PO.Feature,
    CASE WHEN PA.EntityType = '1' THEN 'Computer' ELSE 'User' END [Object Type]
FROM PolicyAssociations PA
INNER JOIN Policies PO
     ON PO.Id = PA.PolicyId
WHERE
    PA.EntityType IN ('1','2') -- Why are these values not INTs?
ORDER by PO.Name, PA.EntityName;

A: Do you just mean this?  Seems too basic of a solution.
SELECT
    PA.EntityName,
    CASE WHEN EntityType = '1' THEN 'Computer'
        WHEN EntityType = '2' THEN 'User'END as EntityTypeStr,
    PA.EntityType,
    PO.Name,
    PO.Feature
FROM PolicyAssociations PA
JOIN Policies PO ON PO.Id = PA.PolicyId
WHERE
    PA.EntityType='1'
    or
    PA.EntityType='2'


text:
Q: How to find duplicate entry in Solidity array I'm writing a function that is supposed to receive an array of uint's and I want to make a requirement that none of the elements in the array be the same and that all of the elements in the array be part of the pre-selected elements to belong in an array. So far I have:
    function vote(uint[] memory proposals) external
    {
        Voter storage sender = voters[msg.sender];
        require(sender.weight != 0, "Has no right to vote.");
        require(!sender.voted, "Already voted.");
        mapping(uint => bool) duplicateVotes;
        require(!duplicateVotes, "Cannot vote for a proposal more than once.");
        sender.voted = true;
        sender.vote = proposals;

        proposals[proposals].voteCount += sender.weight;
    }

But I get an error:
The data location must be "storage", "memory" or "calldata" for variable, but none was given.

But I think this error is just a symptom of a larger problem. Can anyone help me figure out a solution to this problem?

A: I think u want to achieve that same person does not vote twice but the way you are doing is computationally expensive and this will cost too much gas. Instead, crate a mapping to keep track if voter has voted before:
 mapping(address=>bool) peopleWhoVoted;

also you want to keep array of voters
 address[] public listOfVoters;

So in your vote function, make sure that caller of this function-msg.sender is not in the peopleWhoVoted mapping
    function vote(pass argument) public {
       // msg.sender is globally available, it is function caller
       require(!peopleWhoVoted[msg.sender],"this caller already voted")
       // now u are sure that this caller did not vote before
       // so u can add the function caller to the array
       listOfVoters.push(msg.sender)
   }

A: // SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract findDupli {
uint[] public arr = [2,3,4,8,1,7,8];
function funFind() public view returns(uint) {
    uint temp;
    for(uint i = 0; i < arr.length; i++) {
        temp = arr[i];
        for(uint j = 0; j < arr.length; j++) {
            if((j != i) && (temp == arr[j])) {
                return temp;
            }
        }
    }
}

}


text:
Q: What is the actual memory usage of unix domain sockets on Linux if only few bytes are transferred at a time Unix domain sockets under Linux have a default buffer size of 163840 bytes / 160kiB (32bit) or 212992 bytes / 208kiB (64bit), as is explained here:
https://unix.stackexchange.com/questions/424380/what-values-may-linux-use-for-the-default-unix-socket-buffer-size.  These sizes can be adjusted with setsockopt, as explained here: Maximum length of buffer in AF_UNIX socket
However, assume a socket is created with default buffer size, but during its use there will be only small amounts of data transferred, such that the socket never fills up beyond, say, 1kiB of data.  There will be many exchanges like this during the life time of the socket, but at any moment there will only be a few bytes inside.
Will this socket then nevertheless truly occupy the 160kiB / 208kiB, or will only be, say, 2 pages of memory actually be used (one for each direction)?  I could imagine, for example, that the overcommit mechanism is also used for socket memory (which would to be effective also require that the kernel always re-locates the data in the socket rather than having a sliding-window through the buffer).
Background of the question: I would like to know whether it is worth to optimize socket memory usage with setsockopt, or whether the kernel's socket memory management will take care of this anyway.  In the latter case, manual configuration with setsockopt might even better be avoided to avoid problems due to misconfigurations...


text:
Q: how to declare a f# method with list of tuple as parameter? How to write a F# method equal to the below c# code? tried to google it but couldn't find any working ones. thanks.
public List<Tuple<long, string, string>> Fun(List<Tuple<long, string>> param)
{
  var ret = new List<Tuple<long, string, string>>();

  foreach (var tuple in param)
  {
    ret.Add(new Tuple<long, string, string>(tuple.Item1, tuple.Item2, "new val"));
  }

  return ret;
}

A: If you want to use idiomatic functional lists, then you can write:
let func (param:(int64 * string) list) =
  [ for n, s in param -> n, s, "new val" ]

I added the annotation (int64 * string) list to make sure that you get the same type as the one in your C#. If you didn't add it, then the F# compiler would infer the function to be generic - because it actually does not matter what is the type of the first two elements of the tuple. The annotation can be also written in a C# style notation using param:list<int64 * string> which might be easier to read.
If you wanted to use .NET List type (which is not usually recommended in F#), you can use the F# alias ResizeArray and write:
let func (param:(int64 * string) ResizeArray) =
  ResizeArray [ for n, s in param -> n, s, "new val" ]

This creates an F# list and then converts it to .NET List<T> type. This should give you exactly the same public IL signature as the C# version, but I would recommend using F# specific types.
As a side-note, the second example could be implemented using imperative F# code (using for to iterate over the elements just like in C#). This generates exactly the same IL as C#, but this is mainly useful if you need to optimize some F# code later on. So I do not recommend this version (it is also longer :-)):
let func (param:(int64 * string) ResizeArray) =
  let res = new ResizeArray<_>()
  for n, s in param do
    res.Add(n, s, "new val")
  res

You could also use higher-order functions like List.map and write:
let func (param:(int64 * string) list) =
  params |> List.map (fun (n, s) -> n, s, "new val")

A: Here is a literal translation:
member __.Fun (param:ResizeArray<int64 * string>) =
    ResizeArray(param |> Seq.map (fun (a, b) -> a, b, "new val"))

This isn't very idiomatic, however.


text:
Q: Pass by ref is not effectively used inside body - PhpStorm, why is it "bad"? Why I was browsing my code with PhpStorm, I bumped into a "warning":

I know PhpStorm tries to offer "clean" way of coding, but that case I don't understand. What's wrong with that code? $item is unset-ted at the end of foreach.

A: do you use the $item variable inside of your foreach loop? If not, there's no need to pass it by reference.


text:
Q: Angular APP_INITIALIZER circular dependencies at runtime I have a circular dependency (at run-time!) problem, which I don't see how to resolve.
I have registered an APP_INITIALIZER load function, which loads a config.json file. This config file contains among others the LogLevel for NGXLogger.
The config file is loaded through angular's HttpClient.
Besides that, I have registered an HttpInterceptor, which uses the NGXLogger.
It seems that angular tries to resolve everything in this order:

*

*APP_INITIALIZER, so run this function first

*Load function of the initializer triggers a http call, so first run through the interceptor

*Load dependencies of the HttpInterceptor => NGXLogger

*Configure providers for the NGXLogger => based on the configuration file in APP_INITIALIZER

*Throw error, config is undefined

How can I resolve this circular dependencies? Is there a way to completely skip the interceptor on the APP_INITIALIZER http call?
CoreModule.ts:
export function appConfigFactory(configService: AppConfigService) {
  return () => configService.load();
}

export function loggerConfigFactory(configService: AppConfigService): {
  return () => {
    level: (NgxLoggerLevel as any)[configService.config.logLevel] || NgxLoggerLevel.ERROR,
  };
}

@NgModule({
  ...
  providers: [{
    provide: APP_INITIALIZER,
    useFactory: appConfigFactory,
    deps: [AppConfigService],
    multi: true
  }, {
    provide: NgxLoggerConfig,
    useFactory: loggerConfigFactory,
    deps: [AppConfigService]
  }]
})
export class CoreModule {}

AppConfigService.ts:
export class AppConfigService {
  constructor(private http: HttpClient) {}

  load() {
    return this.http
      .get<AppConfig>(`/assets/configuration/${environment.configFile}`)
      .pipe(
        tap((config: any) => {
          this.config = config;
        })
      )
      .toPromise();
  }
}

FakeBackendInterceptor:
@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor {
    constructor(private configService: AppConfigService, private logger: NGXLogger) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // config is undefined here the first time
        if (!this.configService.config || !this.configService.config.mock === 'true') {
            return next.handle(request);
        }
        this.logger.info('Intercepting request with mock');
        // do things
        ...
        return next.handle(request);
    }
}

A: You can use HttpBackend to skip the interceptor in the config service
constructor(
    private http: HttpClient,
    private httpBackend: HttpBackend) { }

And in the load method
const httpClient = new HttpClient(this.httpBackend);
httpClient.get<AppConfig>(`/assets/configuration/${environment.configFile}`)
.pipe(
    tap((config: any) => {
      this.config = config;
    })
  )
  .toPromise();


text:
Q: unbindService vs. stopService I have an single Activity application that starts a Service and binds to it.
I want the Service to continue to run even after I exit the Activity.
Right now I am doing a stopService then an unbindService.  My assumption is that I do need to unbind but to keep it running I shouldn't (obviously) call stopService, right?
I just want to know the proper service management techniques for a long running service.

A: This one can be answered from the Service documentation:

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed. See the Service documentation for more details on a service's lifecycle.

To clean up your service, it is good practice to unbind it.  You can always restart it again using another intent with a Context.startService().  Depending on how you use it, it might be optimal to start the service for a while, do some stuff, stop it (you can even use a call to stopSelf to do this), and then restart it again when you have more work to do -- or get another intent.


text:
Q: Manually populating modelformset Django for testing I have a problem with the error django.forms.utils.ValidationError: ['ManagementForm data is missing or has been tampered with'], but it only occurs in testing my code. When rendering the actual webpage with a real POST-request it does not throw this error.
I have a model called Position and the formset consists of its Candidate-objects. So for a particular position, I may have 4 candidates.
models.py
class Candidate(models.Model):
    user = models.ForeignKey(User, related_name="candidate")
    votes = models.PositiveIntegerField(verbose_name="Antall stemmer", blank=True, default=0)

class Position(models.Model):
    # Candidates running for position
    candidates = models.ManyToManyField(Candidate, blank=True, related_name="positions")

    # Number of people voting
    number_of_voters = models.PositiveIntegerField(default=0, verbose_name="Antall stemmesedler avgitt")

forms.py
class AddPrevoteForm(forms.ModelForm):
    class Meta:
        model = Position
        fields = ['number_of_voters']

class AddPreVoteToCandidateForm(forms.ModelForm):
    class Meta:
        model = Candidate
        fields = ['votes']

    def __init__(self, *args, **kwargs):
        super(AddPreVoteToCandidateForm, self).__init__(*args, **kwargs)
        self.fields['votes'].label = self.instance.user.get_full_name()

views.py
@permission_required('elections.add_election')
@login_required
def admin_register_prevotes(request, pk):
    # Fetch position
    position = get_object_or_404(Position, pk=pk)
    # For for editing total number of people prevoting
    prevote_form = AddPrevoteForm(request.POST or None, instance=position)
    # Form for adjusting individual candidate's votes
    CandidateFormSet = modelformset_factory(
        Candidate, form=AddPreVoteToCandidateForm, extra=0
        )
    formset = CandidateFormSet(
        request.POST or None,
        queryset=position.candidates.all()
        )
    if request.method == 'POST':
        if formset.is_valid() and prevote_form.is_valid():
            for form in formset:
                # Increment both candidate and positions votes
                candidate_pk = form.instance.pk
                candidate = Candidate.objects.get(pk=candidate_pk)
                old_votes = candidate.votes
                new_votes = form.cleaned_data['votes']
                position.total_votes += (new_votes - old_votes)
                form.save()
            prevote_form.save()
            return redirect(reverse(
                'elections:admin_register_candidates',
                kwargs={'pk': position.id}
                ))
    context = {
        'prevote_form': prevote_form,
        'candidate_formset': formset,
        'position': position
    }
    return render(
        request, 'elections/admin/admin_add_prevotes.html',
        context
        )

and the template
<form method="POST">{% csrf_token %}
        {{ candidate_formset.management_form }}
        {% for candidate_form in candidate_formset %}

            {{ candidate_form }}

        {% endfor %}
        {{ prevote_form }}

            <input class="button is-success" type="submit" value="Add prevotes!"></input>

    </form>

The resulting formset coming from the template looks like the following:
<input type="hidden" name="form-TOTAL_FORMS" value="4" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="4" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS" />

Sindre Bakke:	<input type="number" name="form-0-votes" value="3" min="0" id="id_form-0-votes" /><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" />

Christopher Massey:	<input type="number" name="form-1-votes" value="2" min="0" id="id_form-1-votes" /><input type="hidden" name="form-1-id" value="2" id="id_form-1-id" />

Ann Green:	<input type="number" name="form-2-votes" value="0" min="0" id="id_form-2-votes" /><input type="hidden" name="form-2-id" value="3" id="id_form-2-id" />

Michelle Murray:	<input type="number" name="form-3-votes" value="0" min="0" id="id_form-3-votes" /><input type="hidden" name="form-3-id" value="4" id="id_form-3-id" />

which is why I tried the following test (the four first in post_data being from management_form)
@pytest.mark.django_db
def test_add_pre_votes_to_candidate(
        client, create_admin_user,
        create_open_election_with_position_and_candidates):
    admin = create_admin_user
    client.login(username=admin.username, password='defaultpassword')
    election = create_open_election_with_position_and_candidates
    position = election.positions.all().first()
    number_of_candidates = position.candidates.all().count()
    candidate = position.candidates.all().first()
    post_data = {
        'form-TOTAL_FORMS:': '4',
        'form-INITIAL_FORMS': '4',
        'form-MIN_NUM_FORMS': '0',
        'form-MAX_NUM_FORMS': '1000',
        'form-0-votes': '3',
        'form-0-id': 1,
        'form-1-votes': '2',
        'form-1-id': 2,
        'form-2-votes': '0',
        'form-2-id': 3,
        'form-3-votes': '0',
        'form-3-id': 4,
        'number_of_voters': '0'
    }
    client.post(
        reverse(
            'elections:admin_register_prevotes',
            kwargs={'pk': position.id}
            ),
        data=post_data
    )

Any help would be greatly appreciated!

A: This is typically due to the Management form having some issues.
There seems to be a typo in the post_data, 'form-TOTAL_FORMS:' has an extra : at the end in the string.
Also, be careful with implicit primary keys in your unittest. Depending on the implementation of your fixtures that provides the Candidates objects, their IDs in the database might not always be starting at 1,2,.. etc.


text:
Q: how to create a table with result set in sql server I want to create a table to store result set of another query.
I have tried this:
create table avgcost_product (
    name varchar(50),
    productnumber varchar(50),
    averagecost money
)

After creating table I tried this query:
INSERT into avgcost_product SELECT * FROM
(SELECT p.[Name], p.ProductNumber,
        CONVERT(varchar, cost.AvgCost,1) as 'Average Cost'
FROM Production.Product p
CROSS APPLY fnGetAvgCost(p.ProductID) as cost
WHERE cost.AvgCost IS NOT NULL
ORDER BY cost.AvgCost desc)

But it shows error like:

Msg 1033, Level 15, State 1, Line 284
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

How I can write data I need in my table?

A: Just remove the ORDER BY from the inner select or you can even simplify your query even more:
INSERT into avgcost_product
SELECT p.[Name]
       , p.ProductNumber
       , CONVERT(varchar, cost.AvgCost,1) as 'Average Cost'
FROM Production.Product p
CROSS APPLY fnGetAvgCost(p.ProductID) as cost
WHERE cost.AvgCost IS NOT NULL

A: Also you can create the table on the fly using SELECT INTO:
SELECT  p.[Name],
        p.ProductNumber,
        CONVERT(varchar, cost.AvgCost,1) as [Average Cost]
INTO avgcost_product
FROM Production.Product p
CROSS APPLY fnGetAvgCost(p.ProductID) as cost
WHERE cost.AvgCost IS NOT NULL


text:
Q: displaying ground overlay completely inside polygon boundaries in google maps I am trying to display Ground Overlay completely inside polygon boundaries. I tried increasing latitude and longitude by some meters, but the result is not as I expected please help me.
This is my image:

                        double meters = widthtemp2;
                    double coef = meters * 0.0000089;
                    double new_lat = newlatlngs.latitude + coef;
                    double new_long = newlatlngs.longitude + coef / Math.cos(newlatlngs.latitude * 0.018);

                  LatLng finallatlng = new LatLng(new_lat, new_long);
                    mGroundOverlay = mMap.addGroundOverlay(new GroundOverlayOptions()
                            .image(mImages.get(mCurrentEntry))
                            .position(finallatlng, (float) (0.985*widthpanel), (float) (1.646*heightpanel)));


text:
Q: Add Dynamically Value in ngFor I want to add display value(in <mat-option>) dynamically using ngFor. In my HTML code i have added {{'selected'+ displayValue}} under <mat-option> and displayValue is defined in Class. Can somebody help on this.
Thanks.
<mat-form-field>
  <mat-select placeholder="Favorite food" [(ngModel)]="selectedValueModel" (ngModelChange)="changedValue($event)"
    name="food" [compareWith]="compFn">
    <mat-option *ngFor="let selected of SelectedObjectData" [value]="selected">
      {{'selected' + displayValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

export class SelectboxComponent {

  displayValue = 'viewValue'

  SelectedObjectData: any[] = [{ value: 'steak-0', viewValue: 'Steak' },
  { value: 'pizza-1', viewValue: 'Pizza' },
  { value: 'tacos-2', viewValue: 'Tacos' }];

  @Input() selectedValueModel = { value: 'tacos-2', viewValue: 'Tacos' };

  @Output() selectedValueModelChange = new EventEmitter()

  changedValue(newValue: any) {
    this.selectedValueModel = newValue
    this.selectedValueModelChange.emit(newValue)
  }

  compFn(c1: any, c2: any): boolean {
    return c1 && c2 ? c1.value === c2.value : c1 === c2;
  }
}

A: You can use this in your html mat-option
{{selected[displayValue]}}

Check Here: https://stackblitz.com/edit/angular-material-with-angular-v5-my8wzh?embed=1&file=app/app.component.html

A: I think you have gotten your bindings wrong. Your displayValue will always display the string 'viewvalue' on your view. In order to show the display the selected food and the other options, you need to make use of the access the binded selected object, and select the viewValue string property to be displayed on view.
I have made the relevant edited below.
component.html:
<mat-form-field>
    <mat-select placeholder="Favorite food"
   [(ngModel)]="selectedValueModel"
   (ngModelChange)="changedValue($event)" name="food" [compareWith]="compFn">
      <mat-option *ngFor="let selected of SelectedObjectData" [value]="selected">
        {{'selected'+ selected.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>

component.ts:
export class SelectboxComponent {

  displayValue= 'viewValue'

    SelectedObjectData: any[] = [{ value: 'steak-0', viewValue: 'Steak' },
    { value: 'pizza-1', viewValue: 'Pizza' },
    { value: 'tacos-2', viewValue: 'Tacos' }];

  @Input() selectedValueModel = {value: 'tacos-2', viewValue: 'Tacos'};

  @Output() selectedValueModelChange = new EventEmitter()

  changedValue(newValue: any) {
    //this.selectedValueModel = newValue
    //this.selectedValueModelChange.emit(newValue)

    // selected value will be reflected here, do what you want with the newValue object
    console.log(newValue)
  }

  compFn(c1: any, c2: any): boolean {
    return c1 && c2 ? c1.value === c2.value : c1 === c2;
  }
}


text:
Q: How to properly use Jquery to disable checkboxes in a Django Form when a certain number of them are checked I've been trying a couple of ways to disable checkboxes in a Django ModelForm. Using Jquery I was able to write some code that does disable checkboxes when a certain number is checked, but it also disables the ones that have been checked. I want a dynamic way to check and uncheck boxes and only block boxes that have not been checked when the limit is hit.
This is my JS:
function checkBoxes() {

        $(' input[type=checkbox]').
            attr('disabled', true);

        $(document).on('click',
            'input[type=checkbox]',
            function (event) {

                if ($(this).is(":checked")) {
                    console.log("1")
                } else {

                    console.log('2')
                }
            });
  }

The issue I'm having trying to figure this out is how to verify if the box has been checked or not because of how I'm creating the checkbox list with Django:

<form method="post">
    {% csrf_token %}
    {{ context.form.as_p }}
    <button type="submit">Submit</button>
</form>

How can I fix my JS and be able to enable and disable checkboxes dynamically, meaning when the limit is hit, disable all the unchecked boxes, and when the limit is reduced allow checkboxes to be clicked again?

A: Just use
:checked and :not(:checked) in your jquery selector, like this:

$(document).on('click', 'input[type=checkbox]', function(event) {
  if ($('.checkbox-container input[type=checkbox]:checked').length >= 3) {
    $('.checkbox-container input[type=checkbox]:not(:checked)').attr('disabled', true);
  } else($('.checkbox-container input[type=checkbox]').attr('disabled', false));
});

    <input type="checkbox" id="scales1" name="scales1" checked>
    <input type="checkbox" id="scales2" name="scales2" checked>
    <input type="checkbox" id="scales3" name="scales3">
    <input type="checkbox" id="horns1" name="horns1">
    <input type="checkbox" id="horns2" name="horns2">
    <input type="checkbox" id="horns3" name="horns3">


text:
Q: Adding foldmarks in KOMA-script but NOT scrlttr2 Is there an easy way to add foldmarks in KOMA-script classes?
I am aware of the foldmarks-option in scrlttr2, but that works only in scrlttr2.

A: I am not quite sure if there is a solution for every possible papersize, if you want to stick to the DIN norm. The ratios in the example are according to the ratios of foldmarks on A4 paper. This generates foldmarks on the first page.
Please note that I did not look up the correct positions or lengths for these marks on other paper sizes. With the values of 35.35%, 50% and 70.71% (0.3535, 0.50 & 0.7071) this might not be the right values for non A4 paper.
Also these values are for a small letter head. For a large letter head you might want to adjust them to 1-0.3535, 0.5 and 1-0.7071 accordingly.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{lipsum}
\begin{document}
\begin{tikzpicture}[overlay,remember picture]
\draw ($(current page.north west)!0.3535!(current page.south west)$)--++(0.5cm,0cm);
\draw ($(current page.north west)!0.50!(current page.south west)$)--++(0.8cm,0cm);
\draw ($(current page.north west)!0.7071!(current page.south west)$)--++(0.5cm,0cm);
\end{tikzpicture}
\lipsum
\end{document}


text:
Q: Detach SQL Server database without deleting it? Is there a way to detach a database without deleting it?

A: Detaching a DB will remove it's entry from the internal list of DBs managed by Master but will leave the file there to re-attach.  This often could be perhaps not the best course of action to take but to do it follow the MS docs for detach a database.
You could execute the following but it could fail if users are connected to the database in your instance:
EXEC sp_detach_db 'Databasename', 'true';

You could always run a quick sp_who2 to see who is connected to your database or a more thorough:
select spid, status, loginame, hostname, blocked, db_name(dbid), cmd from master..sysprocesses where db_name(dbid) = 'databasename'

As BradC has answered, taking a database 'offline' is also a good option which has it's own benefit and drawback.  Detaching unlocks the file so you could have the file manipulated while it it detached.  Just note having a database 'offline' can cause your scripts or maintenance tasks that scan all your databases to report failures.  It will still 'see' the database, try to access it, but it will not be able to.  Typically most maintenance scripts I write have logic to handle this but many in the wild do not so just note that.

A: Your question is a little vague, but if you are wanting to work with the database files on disk without SQL losing all the meta-data about the database, then what you want is to take the database offline:
ALTER DATABASE database_name SET OFFLINE;

The database still shows in the server list, but can't be accessed until you bring it back online.
This statement may fail if there are active connections. To force it, use WITH ROLLBACK IMMEDIATE:
ALTER DATABASE database_name
SET OFFLINE WITH ROLLBACK IMMEDIATE

Now move your files around, and make sure to tell SQL where to look for them:
ALTER DATABASE database_name
MODIFY FILE (NAME = logical_name, FILENAME = 'new_path\os_file_name');

Then bring it back online:
ALTER DATABASE database_name SET ONLINE;

A: Instead of detaching a database, its always a wise decision to do backup (and restore to a different server)
Another option using PowerShell is to use dbatools - Dismount-DbaDatabase
e.g. Below comand forcefully detaches (as a caution, I have used -whatif to not perform any action and just to print out what the command will do)

Get-DbaDatabase -SqlInstance sql2016b -Database 'SomeUselessDB' | Detach-DbaDatabase -Force -whatif

If you have a detached db and you need more info on that, dbatools gets you covered using Get-DbaDetachedDatabaseInfo

Get-DbaDetachedDatabaseInfo gathers the following information from detached database files: database name, SQL Server version (compatibility level), collation, and file structure. "Data files" and "Log file" report the structure of the data and log files as they were when the database was detached. "Database version" is the compatibility level.


text:
Q: Push notification to users after nth day I want to send a push notification to user's on the second day after the event has occurred, any idea's how to achieve this.
I've created an audience for this and added user's to exclude group, but it seems to exclude all the users.

A: Seems like the above cannot be achieved on an event level.
I ended up using "Last app engagement" instead.


text:
Q: Django image placement this is how I want to display the pictures

this is how it is displayed

 Hi how are you

Hey! I'm fine. Thanks for asking!

It works in normal HTML but not with Django. Please Help.

A: Try this:
In your template:
{% for a in image_table %}
    {% if  a.image %}

    {% else %}
        No image
    {% endif %}
{% endfor %}

  ×

In your App (exempale name:app_image ) repertory create folder: static/app_image
And add this in your settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = "/static/"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),]


text:
Q: How to save a previously drawn image and load it back when previous or next buttons are pressed for a drawing app based on opengl code I have successfully implemented a drawing app using the GLPaint demo app which makes use of OpenGL. Now my problem is i do not have a way how to implement the previous/next functionality in which the strokes of the previous/next images are shown and i can continue my drawing from where i left earlier.
Any help in guiding me to the right direction is appreciated.
Please find the code as shown below
-(void)showImagePrevious{
NSMutableString *fileName = [NSString stringWithFormat:@"%d.png",self.imageCounter+1];
fileName  = (NSMutableString *)[fileName stringByReplacingOccurrencesOfString:@" " withString:@"_"];
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@", fileName]];

// Write image to PNG
[UIImageJPEGRepresentation([self createImageFromGLView:self], 1.0) writeToFile:jpgPath atomically:YES];

// Create file manager
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];

// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

// Write out the contents of home directory to console
NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
NSLog(@"%d",self.imageCounter);
[imgBackground1 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",self.imageCounter]]];
[self erase];
NSString  *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",[NSString stringWithFormat:@"%d.png",self.imageCounter]]];

NSLog(@"%@",filePath);
NSData *texData = [[NSData alloc] initWithContentsOfFile:filePath];

imgDrawnImage.image =  [[UIImage alloc] initWithData:texData];

if (imgDrawnImage.image == nil)
    NSLog(@"Do real error checking here");

GLuint width = CGImageGetWidth(imgDrawnImage.image.CGImage);
GLuint height = CGImageGetHeight(imgDrawnImage.image.CGImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
void *imageData = malloc( height * width * 4 );
CGContextRef context1 = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );
CGColorSpaceRelease( colorSpace );
CGContextClearRect( context1, CGRectMake( 0, 0, width, height ) );
CGContextTranslateCTM( context1, 0, height - height );
CGContextDrawImage( context1, CGRectMake( 0, 0, width, height ), imgDrawnImage.image.CGImage );

CGContextRelease(context1);

free(imageData);

}
-(void)showImageNext{
NSMutableString *fileName = [NSString stringWithFormat:@"%d.png",self.imageCounter-1];
fileName  = (NSMutableString *)[fileName stringByReplacingOccurrencesOfString:@" " withString:@"_"];
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@", fileName]];

// Write image to PNG
[UIImageJPEGRepresentation([self createImageFromGLView:self], 1.0) writeToFile:jpgPath atomically:YES];

// Create file manager
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];

// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

// Write out the contents of home directory to console
NSLog(@"Documents directory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
NSLog(@"%d",self.imageCounter);
[imgBackground1 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",self.imageCounter]]];
[self erase];
NSString  *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",[NSString stringWithFormat:@"%d.png",self.imageCounter]]];

NSLog(@"%@",filePath);

NSData *texData = [[NSData alloc] initWithContentsOfFile:filePath];

imgDrawnImage.image =  [[UIImage alloc] initWithData:texData];

if (imgDrawnImage.image == nil)
    NSLog(@"Do real error checking here");

GLuint width = CGImageGetWidth(imgDrawnImage.image.CGImage);
GLuint height = CGImageGetHeight(imgDrawnImage.image.CGImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
void *imageData = malloc( height * width * 4 );
CGContextRef context1 = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );
CGColorSpaceRelease( colorSpace );
CGContextClearRect( context1, CGRectMake( 0, 0, width, height ) );
CGContextTranslateCTM( context1, 0, height - height );
CGContextDrawImage( context1, CGRectMake( 0, 0, width, height ), imgDrawnImage.image.CGImage );

//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

CGContextRelease(context1);

free(imageData);
}

This method is used to create an UIImage to be saved in the documents directory and i pass self(MyCanvasView) as an argument
-(UIImage *)createImageFromGLView:(UIView *)glView
{
int width = glView.frame.size.height;
int height = glView.frame.size.width;

NSInteger myDataLength = width * height * 4;
// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// gl renders "upside down" so swap top to bottom into new array.
// there's gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y < height; y++)
{
    for(int x = 0; x < width * 4; x++)
    {
        buffer2[((height - 1) - y) * width * 4 + x] = buffer[y * 4 * width + x];
    }
}
// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);
// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
// make the cgimage
CGImageRef imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
return myImage;
}

Best,
Aditya


text:
Q: Pygame doesn't do anything when I run it I have a MacOS Catalina 10.15.4 and Python 3.8.1. I finally got pygame 1.9.6 to install through the terminal with homebrew,xcode,and xquartz downloaded and imported it in my program. I'm a student and following instructions for a project so all the code has already been provided to me and says that a pygame window should show up. When I run the Python icon on my dock bounces up and down and it prints in the shell "Game console initialized
pygame 1.9.6 Hello from the pygame community. https://www.pygame.org/contribute.html". I've tried to read and mess around with what versions work with what but I'm pretty lost to what else I should be doing. Thanks for the help!
Here is my code:
print("Game console initialized")

import pygame

pygame.init()

screenSize = width,height = 240,180
display = pygame.display.set_mode(screenSize)

starImage = pygame.image.load("star.gif")
starBox = starImage.get_rect()

speed = [3,5]

keepPlaying = True
while keepPlaying:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            keepPlaying = False

    starBox = starBox.move(speed)

    if starBox.left<0 or starBox.right > width:
        speed[0] = - speed[0]

    if starBox.top <0 or starBox.bottom > height:
        speed[1] = - speed[1]

    black = 0,0,0
    display.fill(black)

    display.blit(starImage, starBox)
    pygame.display.flip()

    pygame.time.delay(100)
pygame.display.quit()
pygame.quit()


text:
Q: Merge two list of strings based on a condition I'm trying to create a function to merge two lists and return the sorted output based on year that only contains the tags I wanted, for example:
InputLists = [List1, List2]

List1 = ["2010 11 A", "2011 15 B", "2007 19 A", "2012 16 C"]
List2 = ["2015 8 A", "2016, 7 C", "2011 4 B"]

TagLists = ["A", "C"]

sorted_output = my_function(InputLists, TagLists)

sorted_output = ["2007 19 A", "2010 11 A", "2012 16 C", "2015 8 A", "2016 7 C"]

What would such a function look like?

A: The following function should work:
def my_function(il, tl):
  combined = il[0] + il[1] #combine both input lists
  filtered = [] #create filtered list
  for val in combined: #iterate through elements in combined list
    if val[-1] in tl: #checking if last letter is in tagged list
      filtered.append(val) #if so, add to filtered list
  filtered.sort(key = lambda x: (int)(x[:4])) #sort by year
  return filtered #returning filtered list (our answer)

List1 = ["2010 11 A", "2011 15 B", "2007 19 A", "2012 16 C"]
List2 = ["2015 8 A", "2016, 7 C", "2011 4 B"]
InputLists = [List1, List2]

TagLists = ["A", "C"]

sorted_output = my_function(InputLists, TagLists)

print(sorted_output)

Output:
['2007 19 A', '2010 11 A', '2012 16 C', '2015 8 A', '2016, 7 C']

First, we combine the two lists of our InputLists, List1 and List2. Then, we create a filtered list that will only add elements of combined if the last letter is in tl, our TagLists. Then, we just sort by the year, or by the integer value of the first 4 characters of each element.
Let me know if you need any further help or clarifications! :)

A: if you have only two lists you can replace InputLists = [List1, List2] with InputLists = List1 + List2 and then use:
def is_contain_tag(input, tags):
    for tag in tags:
        if tag in input:
            return True
    return False

def my_function(InputLists, TagLists):
    return sorted([input for input in InputLists if is_contain_tag(input, TagLists)])

also, if you know that the tag is the last character, you can replace is_contain_tag with:
def is_contain_tag(input, tags):
    return len(input) > 1 and input[-1] in tags

also note, that if you don't know if the year apear at the beginning, you need to handle it.

A: This will work with any number of lists of strings within the list that is given to the lists parameter and with any number of strings of various length and characters that are given as a list to the tags parameter. Any tag is considered to be separated from the rest of the string by a whitespace.
def fun(lists,tags):
    flat_list=[]
    result=[]
    for i in lists: #making one-level list
        flat_list+=i
    for i in flat_list:
        if any(i.endswith(' '+tag)==True for tag in tags):
            result[:0]=[i] #adding to the beginning
        else:
            result.append(i) #adding to the end
    return result

A: This is what the function will look like. The code should use a loop to iterate over the tag list to check if the individual tags are in the two lists, that's why both the two lists for loops are under the one for the tag list
def merge_list(lst1,lst2,Taglist):
        sorted_output =[]
        for x in range(len(Taglist)):# loop for the tag list
            for j in range(len(lst1)):# loop for the list 1
                if Taglist[x] in lst1[j]:#this compares items
                    sorted_output.append(lst1[j])
            for i in range(len(lst2)):# loop for the list 2
                if Taglist[x] in lst2[i]:#this compares items
                    sorted_output.append(lst2[i])
        sorted_output = sorted(sorted_output)
        return sorted_output

    List1 = ["2010 11 A", "2011 15 B", "2007 19 A", "2012 16 C"]
    List2 = ["2015 8 A", "2016, 7 C", "2011 4 B"]
    TagLists = ["A", "C"]
    x =  merge_list(List1,List2,TagLists)
    print(x)


text:
Q: Is the area the integral of the perimeter? Let $A$ be a compact subset of the plane with piecewise smooth boundary. Define $A_r$ to be the set $\{x\in \mathbb{R}^2: dist(x,A)\leq r\}$, i.e. the points with distance at most $r$ from $A$. Motivate by the case of a circle, I was wondering if the following formula holds
$$|A_r|=|A|+ \int_{0}^r L(\partial A_s) ds,$$
where $| |$ denotes the area and $L(\partial A_s)$ the perimeter of $A_s$. Does this formula hold in general? What if $A$ is a convex domain or perhaps a finite union of disks?

A: Let $A$ be compact convex in $\mathbb{R}^2$, and let other notations be as in the question. Then Jacob Steiner (1840) proved:
$$\begin{align}
\left\lvert A_r\right\rvert&=\left\lvert A\right\rvert+L(\partial A)r+\mathrm{\pi}r^2\\
L(\partial A_r)&=L(\partial A) +2\mathrm{\pi}r\text{.}
\end{align}$$
For compact convex domains, your equality is an immediate consequence. Nowadays, this Steiner formula is considered to be an early result in integral geometry.

A: In case  $A$ is convex, a formula for $|A_r|$ is
$$ |A_r| = |A| + r L(\partial A) + \pi r^2$$
and a formula for $L(\partial A_s)$ is $$L(\partial A_s) = L(\partial A) + 2\pi s.$$
Your formula arises quickly from here. These are classical theorems of convex geometry. You should be able to find a citation.
If $A$ is a finite union of disks things go bad once the disks comprising $A_r$ start to overlap. In the case of general $A$ I don't think such a formula is valid.


text:
Q: Download iPhoto for Yosemite? How can I download the last iPhoto version for Yosemite?
Looks like any links are invalid now that Photos is out.
And upgrading a pre-Yosemite version does not work. There is an update button but it does not do anything but disable itself when clicked.

A: Have you purchased the iPhoto? If yes, you should see it in App Store > Purchases tab.
EDIT: The problem was: Clicking on "Update" button didn't update application.
Solution: Delete and redownload application.

A: Downloading from "Purchases" works for me (July 2015)


text:
Q: Using LuaTeX, HSRM beamer theme, fontspec says DANTE font not found. .sty file has no reference to DANTE I am attempting to modify the HSRM beamer theme found here. After switching from pdftex to LuaTex and purchasing the Flama fonts, I thought I would be ready to go. However, that seems not to be the case. I am now getting an error saying:
! fontspec error: "font-not-found"
!
! The font "DANTE" cannot be found.
!
! See the fontspec documentation for further information.

It says that I should find a reference to DANTE on line 140 here:
l.140   \newfontface\DANTEFONT{DANTE}

But I don't see that in either the .sty file or the .tex.
I am using the hsrm-beamer-demo.tex and .sty files, not the minimal ones.
Can anyone help me figure out where the heck I'm going wrong?
I'm on a Mac and I'm using Mactex and emacs if that makes any difference.

A: File hsrm-beamer-demo.tex loads package dtklogos, which contains in lines 138 to 147:
\ifluatex
  \RequirePackage{fontspec}
  \newfontface\DANTEFONT{DANTE}
  \providecommand*\DANTE[1][]{\DANTEFONT DANTE}
\else
  \providecommand*\DANTE[1][]{%
      \begingroup
        \usefont{OT1}{dante}{m}{n}\selectfont DANTE%
      \endgroup}
\fi

DANTE is a special font for typesetting the name/logo of the German TeX user group "DANTE e.V.". It is used in the journal "Die TeXnische Komödie" published by the user group.
AFAIK the font is not publicly available. I have addressed it to the presidium around three times with a positive feedback, but nothing happened so far, it is not on CTAN. Probably a low priority/no time issue.
As workaround, the dtklogos.sty can be copied to a new name, e.g. mydtklogos.sty. There the problematic line can be disabled or removed.