问:
Python Logging - Disable logging from imported modules
I'm using the Python logging module, and would like to disable log messages printed by the third party modules that I import.  For example, I'm using something like the following:

```<code>logger = logging.getLogger()
logger.setLevel(level=logging.DEBUG)
fh = logging.StreamHandler()
fh_formatter = logging.Formatter('%(asctime)s %(levelname)s %(lineno)d:%(filename)s(%(process)d) - %(message)s')
fh.setFormatter(fh_formatter)
logger.addHandler(fh)
</code>```

This prints out my debug messages when I do a logger.debug("my message!"), but it also prints out the debug messages from any module I import (such as requests, and a number of other things).

I'd like to see only the log messages from modules I'm interested in.  Is it possible to make the logging module do this?

Ideally, I'd like to be able tell the logger to print messages from "ModuleX, ModuleY" and ignore all others.

I looked at the following, but I don't want to have to disable/enable logging before every call to an imported function:
logging - how to ignore imported module logs?

答:
This disables all existing loggers, such as those created by imported modules, while still using the root logger (and without having to load an external file).

```<code>import logging.config
logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': True,
})
</code>```

Note that you need to import all modules you don't want logged first! Otherwise those won't be considered as "existing loggers". It will then disable all loggers from those modules. This might lead you to also miss out on important errors!

For more detailed examples using related options for configuration, see https://gist.github.com/st4lk/6287746, and here is a (partially working) example using YAML for config with the coloredlog library.

Body:
I'm using the Python logging module, and would like to disable log messages printed by the third party modules that I import.  For example, I'm using something like the following:

logger = logging.getLogger()
logger.setLevel(level=logging.DEBUG)
fh = logging.StreamHandler()
fh_formatter = logging.Formatter('%(asctime)s %(levelname)s %(lineno)d:%(filename)s(%(process)d) - %(message)s')
fh.setFormatter(fh_formatter)
logger.addHandler(fh)

This prints out my debug messages when I do a logger.debug("my message!"), but it also prints out the debug messages from any module I import (such as requests, and a number of other things).

I'd like to see only the log messages from modules I'm interested in.  Is it possible to make the logging module do this?

Ideally, I'd like to be able tell the logger to print messages from "ModuleX, ModuleY" and ignore all others.

I looked at the following, but I don't want to have to disable/enable logging before every call to an imported function:
logging - how to ignore imported module logs?

Body:
This disables all existing loggers, such as those created by imported modules, while still using the root logger (and without having to load an external file).

import logging.config
logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': True,
})

Note that you need to import all modules you don't want logged first! Otherwise those won't be considered as "existing loggers". It will then disable all loggers from those modules. This might lead you to also miss out on important errors!

For more detailed examples using related options for configuration, see https://gist.github.com/st4lk/6287746, and here is a (partially working) example using YAML for config with the coloredlog library.


来源: stackexchange

问:
strtok and it's usage
I'm working on an assignment that requires string and file manipulation. I'm currently working on the string manipulation part and I'm trying to use strtok to separate lines in a file, split by a comma. However, I'm not sure how strtok works. I'm looking at the code below and don't quite understand why there is a NULL in the second strtok call, when NULL isn't even a string.

The code I'm running:

/*****************************************************************
 *
 * Purpose: Program to demonstrate the 'strtok' function.
 * Author:  M J Leslie
 * Date:    23-Apr-94
 *
 ****************************************************************/

```<code>#include <stdio.h>
#include <string.h>

main()
{
            /* Copy the constant into the memory
             * pinted to by 'test_string'       */
    char test_string[50]="string to split up";

    /* if 'test_string' is declared as below and the program will give a
    * 'Segmentation fault' This is because test_string' is pointing
    * to a constant i.e. somethin that cant be changed.

    char *test_string="string to split up";         */

    char *sub_string;

                /* Extract first string */
    printf("%s\n", strtok(test_string, " "));

                /* Extract remaining
                 * strings      */
    while ( (sub_string=strtok(NULL, " ")) != NULL)
    {
         printf("%s\n", sub_string);
    }
 }
 /*****************************************************************
 *
 * Program O/P will look like this...
 *
 *   string
 *   to
 *   split
 *   up
 *
 *****************************************************************/
</code>```

答:
From the documentation:

Each subsequent call, with a null pointer as the value of the first argument, starts searching from the saved pointer and behaves as described above.

ContentLicense: CC BY-SA 3.0

Title: strtok and it's usage

Body:
I'm working on an assignment that requires string and file manipulation. I'm currently working on the string manipulation part and I'm trying to use strtok to separate lines in a file, split by a comma. However, I'm not sure how strtok works. I'm looking at the code below and don't quite understand why there is a NULL in the second strtok call, when NULL isn't even a string.

The code I'm running:

/*****************************************************************
 *
 * Purpose: Program to demonstrate the 'strtok' function.
 * Author:  M J Leslie
 * Date:    23-Apr-94
 *
 ****************************************************************/

#include <stdio.h>
#include <string.h>

main()
{
            /* Copy the constant into the memory
             * pinted to by 'test_string'       */
    char test_string[50]="string to split up";

    /* if 'test_string' is declared as below and the program will give a
    * 'Segmentation fault' This is because test_string' is pointing
    * to a constant i.e. somethin that cant be changed.

    char *test_string="string to split up";         */

    char *sub_string;

                /* Extract first string */
    printf("%s\n", strtok(test_string, " "));

                /* Extract remaining
                 * strings      */
    while ( (sub_string=strtok(NULL, " ")) != NULL)
    {
         printf("%s\n", sub_string);
    }
 }
 /*****************************************************************
 *
 * Program O/P will look like this...
 *
 *   string
 *   to
 *   split
 *   up
 *
 *****************************************************************/


问:
glm rotating quaternion in Y axis deforms object
I'm implementing my own game engine in C++ and I need help here,

I have a game object, its orientation property is a quaternion and I want to rotate it A degrees in the Y axis.

So, I have:

```<code>currentAngle += 0.01; // currentAngle is a member variable, so yes i initialized it
quat q(currentAngle, vec3(0, 1, 0));
myGameObject->SetOrientation(q);

GameObject::SetOrientation(quat q)
{
 myOrientation  = q;
}
</code>```

but as the game object rotates, it also gets scaled (deformed). So I checked how I am applying the transformation matrices

```<code>myModelMatrix = Math::CreateTransformationMatrix(
    transformation->GetPosition(),
    transformation->GetOrientation(),
    transformation->GetScale());

mat4& Math::CreateTransformationMatrix(vec3&    translation, quat& orientation, vec3& scaleSize)
{

     mat4 translate = glm::translate(glm::mat4(), translation);
     mat4 rotate = glm::toMat4(orientation);
     mat4 scale = glm::scale(glm::mat4(), scaleSize);

    return  translate * rotate * scale;
}
</code>```

but it looks ok (at least to me), I removed the scale matrix form the multiplication to check if somehow I was doing something with it. However, it didnt fix anything.

I also tried:

```<code>  quat q(currentAngle, vec3(0, 1, 0));
   quat orientation = myGameObject->GetOrientation();
   orientation  = orientation  *q;
   myGameObject->SetOrientation(orientation);
</code>```

But it didnt work either.
I also checked the code in my shaders and I am positive is not the problem.

This is how I send the matrices to the shader:

```<code>glUseProgram(progarmId);1
    glUniformMatrix4fv(uniforms[name], 1, GL_FALSE, glm::value_ptr(matrix));
</code>```

I tried modifying the 3rd parameter to True and swapping the order of the projection view matrix multiplication and it didnt work either :/

So, guys ... any ideas what could I be doing wrong ? I'm out of ideas :/

答:
So I figured it out.

when I was doing :

```<code>currentAngle += 0.01; // currentAngle is a member variable, so yes i initialized it
quat q(currentAngle, vec3(0, 1, 0));
myGameObject->SetOrientation(q);
</code>```

the quad must be transformed first using angle to axis method from glm, so at the end:

```<code>   currentAngle = 0.01; // currentAngle is a member variable, so yes i initialized it
  //quat q(currentAngle, vec3(0, 1, 0));
    vec3 up(0, 1, 0);
    quat q = glm::angleAxis(currentAngle, up);
    GameObject->Rotate(q);
</code>```

Body:
I'm implementing my own game engine in C++ and I need help here,

I have a game object, its orientation property is a quaternion and I want to rotate it A degrees in the Y axis.

So, I have:

currentAngle += 0.01; // currentAngle is a member variable, so yes i initialized it
quat q(currentAngle, vec3(0, 1, 0));
myGameObject->SetOrientation(q);

GameObject::SetOrientation(quat q)
{
 myOrientation  = q;
}

but as the game object rotates, it also gets scaled (deformed). So I checked how I am applying the transformation matrices

myModelMatrix = Math::CreateTransformationMatrix(
    transformation->GetPosition(),
    transformation->GetOrientation(),
    transformation->GetScale());

mat4& Math::CreateTransformationMatrix(vec3&    translation, quat& orientation, vec3& scaleSize)
{

     mat4 translate = glm::translate(glm::mat4(), translation);
     mat4 rotate = glm::toMat4(orientation);
     mat4 scale = glm::scale(glm::mat4(), scaleSize);

    return  translate * rotate * scale;
}

but it looks ok (at least to me), I removed the scale matrix form the multiplication to check if somehow I was doing something with it. However, it didnt fix anything.

I also tried:

  quat q(currentAngle, vec3(0, 1, 0));
   quat orientation = myGameObject->GetOrientation();
   orientation  = orientation  *q;
   myGameObject->SetOrientation(orientation);

But it didnt work either.
I also checked the code in my shaders and I am positive is not the problem.

This is how I send the matrices to the shader:

glUseProgram(progarmId);1
    glUniformMatrix4fv(uniforms[name], 1, GL_FALSE, glm::value_ptr(matrix));

I tried modifying the 3rd parameter to True and swapping the order of the projection view matrix multiplication and it didnt work either :/

So, guys ... any ideas what could I be doing wrong ? I'm out of ideas :/

Body:
So I figured it out.

when I was doing :

currentAngle += 0.01; // currentAngle is a member variable, so yes i initialized it
quat q(currentAngle, vec3(0, 1, 0));
myGameObject->SetOrientation(q);

the quad must be transformed first using angle to axis method from glm, so at the end:

   currentAngle = 0.01; // currentAngle is a member variable, so yes i initialized it
  //quat q(currentAngle, vec3(0, 1, 0));
    vec3 up(0, 1, 0);
    quat q = glm::angleAxis(currentAngle, up);
    GameObject->Rotate(q);


问:
Jenkins: Can't connect to Docker daemon
I am running Jenkins and Docker on a CentOS machine. I have a Jenkins job that pulls a Github repo and builds a Docker image. When I try running the job I get the error:

```<code>+ docker build -t myProject .
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code>```

This problem occurs even though I have added jenkins to my docker usergroup via sudo usermod -aG docker jenkins and restarted my machine. How do I fix this?

By the way, if try changing the command to sudo docker build -t myProject . I just get the error sudo: sorry, you must have a tty to run sudo

答:
@lvthillo, your answer is good, but, not enough.  You also need to create the docker group.  See Post Installation Steps for Docker  Manage Docker as a non-root user
 https://docs.docker.com/engine/installation/linux/linux-postinstall/#manage-docker-as-a-non-root-user

to add the user running jenkins to the docker group.

E.g. if you run Jenkins server under the jenkins user:

Step 1: Create Docker Group

```<code>sudo groupadd docker
</code>```

Step 2: Add your user to the docker group:

```<code>sudo usermod -aG docker jenkins
</code>```

Step 3: Logout and log back in as jenkins, then test:

```<code>docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
</code>```

The docker group is given special treatement by the docker daemon on startup just for this purpose.  Any user in that group can now call docker without sudo.  Use this with care.

https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface

ContentLicense: CC BY-SA 4.0

Title: Jenkins: Can't connect to Docker daemon

Body:
I am running Jenkins and Docker on a CentOS machine. I have a Jenkins job that pulls a Github repo and builds a Docker image. When I try running the job I get the error:

+ docker build -t myProject .
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
Build step 'Execute shell' marked build as failure
Finished: FAILURE

This problem occurs even though I have added jenkins to my docker usergroup via sudo usermod -aG docker jenkins and restarted my machine. How do I fix this?

By the way, if try changing the command to sudo docker build -t myProject . I just get the error sudo: sorry, you must have a tty to run sudo

Body:
@lvthillo, your answer is good, but, not enough.  You also need to create the docker group.  See Post Installation Steps for Docker  Manage Docker as a non-root user
 https://docs.docker.com/engine/installation/linux/linux-postinstall/#manage-docker-as-a-non-root-user

to add the user running jenkins to the docker group.

E.g. if you run Jenkins server under the jenkins user:

Step 1: Create Docker Group

sudo groupadd docker

Step 2: Add your user to the docker group:

sudo usermod -aG docker jenkins

Step 3: Logout and log back in as jenkins, then test:

docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

The docker group is given special treatement by the docker daemon on startup just for this purpose.  Any user in that group can now call docker without sudo.  Use this with care.

https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface


问:
What type of orthogonal polynomials does R use?
I was trying to match the orthogonal polynomials in the following code in R:

```<code>X <- cbind(1, poly(x = x, degree = 9))
</code>```

but in python.

To do this I implemented my own method for giving orthogonal polynomials:

```<code>def get_hermite_poly(x,degree):
    #scipy.special.hermite()
    N, = x.shape
    ##
    X = np.zeros( (N,degree+1) )
    for n in range(N):
        for deg in range(degree+1):
            X[n,deg] = hermite( n=deg, z=float(x[deg]) )
    return X
</code>```

though it does not seem to match it. Does someone know type of orthogonal polynomial it uses? I tried search in the documentation but didn't say.

To give some context I am trying to implement the following R code in python (https://stats.stackexchange.com/questions/313265/issue-with-convergence-with-sgd-with-function-approximation-using-polynomial-lin/315185#comment602020_315185):

```<code>set.seed(1234)

N <- 10
x <- seq(from = 0, to = 1, length = N)
mu <- sin(2 * pi * x * 4)
y <- mu
plot(x,y)

X <- cbind(1, poly(x = x, degree = 9))
# X <- sapply(0:9, function(i) x^i)
w <- rnorm(10)

learning_rate <- function(t) .1 / t^(.6)

n_samp <- 2
for(t in 1:100000) {
  mu_hat <- X %*% w
  idx <- sample(1:N, n_samp)
  X_batch <- X[idx,]
  y_batch <- y[idx]
  score_vec <- t(X_batch) %*% (y_batch - X_batch %*% w)

  change <- score_vec * learning_rate(t)
  w <- w + change
}

plot(mu_hat, ylim = c(-1, 1))
lines(mu)
fit_exact <- predict(lm(y ~ X - 1))
lines(fit_exact, col = 'red')
abs(w - coef(lm(y ~ X - 1)))
</code>```

because it seems to be the only one that works with gradient descent with linear regression with polynomial features.

I feel that any orthogonal polynomial (or at least orthonormal) should work and give a hessian with condition number 1 but I can't seem to make it work in python. Related question: How does one use Hermite polynomials with Stochastic Gradient Descent (SGD)?

答:
poly uses QR factorization, as described in some detail in this answer.

I think that what you really seem to be looking for is how to replicate the output of R's poly using python.

Here I have written a function to do that based on R's implementation.  I have also added some comments so that you can see the what the equivalent statements in R look like:

```<code>import numpy as np

def poly(x, degree):
    xbar = np.mean(x)
    x = x - xbar

    # R: outer(x, 0L:degree, "^")
    X = x[:, None] ** np.arange(0, degree+1)

    #R: qr(X)$qr
    q, r = np.linalg.qr(X)

    #R: r * (row(r) == col(r))
    z = np.diag((np.diagonal(r)))

    # R: Z = qr.qy(QR, z)
    Zq, Zr = np.linalg.qr(q)
    Z = np.matmul(Zq, z)

    # R: colSums(Z^2)
    norm1 = (Z**2).sum(0)

    #R: (colSums(x * Z^2)/norm2 + xbar)[1L:degree]
    alpha = ((x[:, None] * (Z**2)).sum(0) / norm1 +xbar)[0:degree]

    # R: c(1, norm2)
    norm2 = np.append(1, norm1)

    # R: Z/rep(sqrt(norm1), each = length(x))
    Z = Z / np.reshape(np.repeat(norm1**(1/2.0), repeats = x.size), (-1, x.size), order='F')

    #R: Z[, -1]
    Z = np.delete(Z, 0, axis=1)
    return [Z, alpha, norm2];
</code>```

Checking that this works:

```<code>x = np.arange(10) + 1
degree = 9
poly(x, degree)
</code>```

The first row of the returned matrix is

```<code>[-0.49543369,  0.52223297, -0.45342519,  0.33658092, -0.21483446,
  0.11677484, -0.05269379,  0.01869894, -0.00453516],
</code>```

compared to the same operation in R

```<code>poly(1:10, 9)
# [1] -0.495433694  0.522232968 -0.453425193  0.336580916 -0.214834462
# [6]  0.116774842 -0.052693786  0.018698940 -0.004535159
</code>```

Body:
I was trying to match the orthogonal polynomials in the following code in R:

X <- cbind(1, poly(x = x, degree = 9))

but in python.

To do this I implemented my own method for giving orthogonal polynomials:

def get_hermite_poly(x,degree):
    #scipy.special.hermite()
    N, = x.shape
    ##
    X = np.zeros( (N,degree+1) )
    for n in range(N):
        for deg in range(degree+1):
            X[n,deg] = hermite( n=deg, z=float(x[deg]) )
    return X

though it does not seem to match it. Does someone know type of orthogonal polynomial it uses? I tried search in the documentation but didn't say.

To give some context I am trying to implement the following R code in python (https://stats.stackexchange.com/questions/313265/issue-with-convergence-with-sgd-with-function-approximation-using-polynomial-lin/315185#comment602020_315185):

set.seed(1234)

N <- 10
x <- seq(from = 0, to = 1, length = N)
mu <- sin(2 * pi * x * 4)
y <- mu
plot(x,y)

X <- cbind(1, poly(x = x, degree = 9))
# X <- sapply(0:9, function(i) x^i)
w <- rnorm(10)

learning_rate <- function(t) .1 / t^(.6)

n_samp <- 2
for(t in 1:100000) {
  mu_hat <- X %*% w
  idx <- sample(1:N, n_samp)
  X_batch <- X[idx,]
  y_batch <- y[idx]
  score_vec <- t(X_batch) %*% (y_batch - X_batch %*% w)

  change <- score_vec * learning_rate(t)
  w <- w + change
}

plot(mu_hat, ylim = c(-1, 1))
lines(mu)
fit_exact <- predict(lm(y ~ X - 1))
lines(fit_exact, col = 'red')
abs(w - coef(lm(y ~ X - 1)))

because it seems to be the only one that works with gradient descent with linear regression with polynomial features.

I feel that any orthogonal polynomial (or at least orthonormal) should work and give a hessian with condition number 1 but I can't seem to make it work in python. Related question: How does one use Hermite polynomials with Stochastic Gradient Descent (SGD)?

Body:
poly uses QR factorization, as described in some detail in this answer.

I think that what you really seem to be looking for is how to replicate the output of R's poly using python.

Here I have written a function to do that based on R's implementation.  I have also added some comments so that you can see the what the equivalent statements in R look like:

import numpy as np

def poly(x, degree):
    xbar = np.mean(x)
    x = x - xbar

    # R: outer(x, 0L:degree, "^")
    X = x[:, None] ** np.arange(0, degree+1)

    #R: qr(X)$qr
    q, r = np.linalg.qr(X)

    #R: r * (row(r) == col(r))
    z = np.diag((np.diagonal(r)))

    # R: Z = qr.qy(QR, z)
    Zq, Zr = np.linalg.qr(q)
    Z = np.matmul(Zq, z)

    # R: colSums(Z^2)
    norm1 = (Z**2).sum(0)

    #R: (colSums(x * Z^2)/norm2 + xbar)[1L:degree]
    alpha = ((x[:, None] * (Z**2)).sum(0) / norm1 +xbar)[0:degree]

    # R: c(1, norm2)
    norm2 = np.append(1, norm1)

    # R: Z/rep(sqrt(norm1), each = length(x))
    Z = Z / np.reshape(np.repeat(norm1**(1/2.0), repeats = x.size), (-1, x.size), order='F')

    #R: Z[, -1]
    Z = np.delete(Z, 0, axis=1)
    return [Z, alpha, norm2];

Checking that this works:

x = np.arange(10) + 1
degree = 9
poly(x, degree)

The first row of the returned matrix is

[-0.49543369,  0.52223297, -0.45342519,  0.33658092, -0.21483446,
  0.11677484, -0.05269379,  0.01869894, -0.00453516],

compared to the same operation in R

poly(1:10, 9)
# [1] -0.495433694  0.522232968 -0.453425193  0.336580916 -0.214834462
# [6]  0.116774842 -0.052693786  0.018698940 -0.004535159


问:
An hello world app ,but cause err "image not found"
Just a Hello world app.
I create a view-based appllication named it Hello World.
then save ,build and
I double click the app under products.
cause the error:

```<code>Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000
Crashed Thread:  0
Dyld Error Message:
  Library not loaded: /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
  Referenced from: /Users/myname/Documents/Control Fun/build/Debug-iphonesimulator/Control Fun.app/Control Fun
  Reason: image not found
</code>```

I googled and tyied many ideas.Unluckily I can't slove it.
Thanks in advance!

答:
Plz check you project has CoreGraphics.framework. It would be defaulty included..but you might remove it by mistake.

You can check included frameworks on "General Tap" of project info.

ContentLicense: CC BY-SA 2.5

Body:
Just a Hello world app.
I create a view-based appllication named it Hello World.
then save ,build and
I double click the app under products.
cause the error:

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000
Crashed Thread:  0
Dyld Error Message:
  Library not loaded: /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
  Referenced from: /Users/myname/Documents/Control Fun/build/Debug-iphonesimulator/Control Fun.app/Control Fun
  Reason: image not found

I googled and tyied many ideas.Unluckily I can't slove it.
Thanks in advance!


问:
when file couldn't be opened in c++, I want it to end the program, and not output more stuff
when file couldn't be opened in c++, I want it to end the program, and not output more stuff!

my code:

```<code>#include<iostream>
#include <fstream>
#include<stdlib.h>
using namespace std;

// Function to accept a file names from the user and read file contents
// First Parameter: Student Answer file
// Second Parameter: Correct Answer file
// Third Parameter: Character type array to store student answers
// Fourth Parameter: Character type array to store correct answers
void readFile(string fileStuAns, string fileCorrAnswer, char sAns[], char           cAns[])
{
    // Initialize the line counter to zero
    int counter = 0;
    // Creates ifstream class objects
    ifstream inSFile, inCFile;
    // Opens the file for reading data from text file student answer
    inSFile.open (fileStuAns.c_str());
    // Opens the file for reading data from text file for correct answer
    inCFile.open (fileCorrAnswer.c_str());
    // Checks if student answer file can be opened or not
    if(inSFile.fail())
    {
        // Displays error message
        cout<<"File "<<"\""<<fileStuAns<<"\""<< " could not be opened"<<endl;
        return;
    }// End of if condition
     // Checks if file can be opened or not
    if(inCFile.fail())
    {
        // Displays error message
        cout<<"File "<<"\""<<fileCorrAnswer<<"\""<< " could not be opened";
        return;
    }// End of if condition
     // Loops till end of the student answer file
    while(!inSFile.eof())
    {
        // Reads data from file and stores student answer character array's counter      index position
        inSFile>>sAns[counter];
        // Increase the current line counter by one
        counter++;
    }// End of while
     //Close student answer file
    inSFile.close();
    // Reset the counter to zero
    counter = 0;
    // Loops till end of correct answer the file
    while(!inCFile.eof())
    {
        // Reads data from file and stores correct answer character array's counter      index position
        inCFile>>cAns[counter];
        // Increase the current line counter by one
        counter++;
    }// End of while

     // Close correct answer file
    inCFile.close();
}// End of function

// Displays the student result
// First Parameter: Character type array contains student answers
// Second Parameter: Character type array contains correct answers
void resultSheet(char sAns[], char cAns[])
{
    // Displays student answers
}// End of function

// Function to write data to file entered by the user
// First Parameter: Invalid Answer file
// Second Parameter: Character type array contains student answers
// Third Parameter: Character type array contains correct answers
void writeTextFile(string fileInAnschar, char sAns[], char cAns[])
{
    // To store number of lines
    int cA, iA;
    cA = iA = 0;
    // ofstream class object created
    ofstream outFile;
    // Opens the file for writing onto a text file
    outFile.open(fileInAnschar.c_str());
    // Checks if file can be opened or not
    if(outFile.fail())
    {
        // Displays error message
        cout<<"\n Error: Unable to open "<<fileInAnschar;
        return;
    }// End of if condition
     // Loops till 20 times for 20 questions

    for(int c = 0; c < 20; c++)
    {
        // If student answers current index position value is not equals to correct      answer's current index position
        if(sAns[c] != cAns[c])
        {
            // Writes the result to the file
            outFile<<"Question "<<(c + 1)<<" has incorrect answer "<<"'"<<sAns[c]<<"'" <<", the correct answer is "<<"'"<<cAns[c]<<"'"<<endl;
            // Displays the result
            cout<<"Question "<<(c+1)<<" has incorrect answer "<<"'"<<sAns[c]<<"'"<<",      the correct answer is "<<"'"<<cAns[c]<<"'"<<endl;
            // Increase the counter by one
            iA++;
        }// End of if condition
    }// End of for loop
     // Calculates number of correct answers
    cA = 20 - iA;
    // Calculates the average
    double percent = cA / 20;
    // Checks if the average is greater than or equals 70
    if(iA <= 6)
    {
        // Displays the result
        cout<<iA<<" questions were missed"<<endl;
        cout<<"The student passed"<<endl;
    }// End of if condition
     // Otherwise fail
    else
    {
        cout<<iA<<" questions were missed"<<endl;
        cout<<"The student failed"<<endl;
    }// End of else
     //Close file
    outFile.close();
}//End of function

// main function definition
int main()
{
    // Character array to store student answers
    char studentAnswer[21];
    // Character array to store correct answers
    char correctAnswer[21];
    // To store the file name
    string fileNameStu, fileNameCorr;
    // Accepts the file name to read

    cin>>fileNameStu;

    cin>>fileNameCorr;
    // Calls the file to read student answer and correct answer and stores it in respective arrays
    readFile(fileNameStu, fileNameCorr, studentAnswer, correctAnswer);
    // Calls the function to display student answer and correct answer
    resultSheet(studentAnswer, correctAnswer);
    // Accepts the file name to write invalid answers

    cin>>fileNameStu;
    // Calls the function to write invalid answers
    writeTextFile(fileNameStu, studentAnswer, correctAnswer);
}// End of main function
</code>```

My output:

```<code>File "invalidfile.txt" could not be opened

b"Question 1 has incorrect answer '\xf0', the correct answer is '\x00'\nQuestion 2 has incorrect answer ';', the correct answer is '\x00'\nQuestion 3 has incorrect answer '\xae', the correct answer is '\x00'\nQuestion 4 has incorrect answer '\xa7', the correct answer is '\x00'\nQuestion 5 has incorrect answer '\xff', the correct answer is '\x00'\nQuestion 6 has incorrect answer '\x7f', the correct answer is '\x00'\n"Question 9 has incorrect answer 'T', the correct answer is ''
Question 10 has incorrect answer '', the correct answer is ''
Question 11 has incorrect answer '@', the correct answer is ''
Question 17 has incorrect answer '', the correct answer is 'p'
Question 18 has incorrect answer '', the correct answer is ''
Question 19 has incorrect answer '', the correct answer is '@'

12 questions were missed

The student failed
</code>```

Output should be:

```<code>File "invalidfile.txt" could not be opened
</code>```

Attached picture of output:

答:
A good way to do this is to use the exit command that is in cstdlib.
Basically anytime you throw an error also call exit. For example

```<code>std::cout << "Fatal error: Invalid file" << std::endl;
std::exit(1);
</code>```

exit will terminate the program and by passing the '1' argument, it will terminate "unsuccessfully"

Body:
when file couldn't be opened in c++, I want it to end the program, and not output more stuff!

my code:

#include<iostream>
#include <fstream>
#include<stdlib.h>
using namespace std;

// Function to accept a file names from the user and read file contents
// First Parameter: Student Answer file
// Second Parameter: Correct Answer file
// Third Parameter: Character type array to store student answers
// Fourth Parameter: Character type array to store correct answers
void readFile(string fileStuAns, string fileCorrAnswer, char sAns[], char           cAns[])
{
    // Initialize the line counter to zero
    int counter = 0;
    // Creates ifstream class objects
    ifstream inSFile, inCFile;
    // Opens the file for reading data from text file student answer
    inSFile.open (fileStuAns.c_str());
    // Opens the file for reading data from text file for correct answer
    inCFile.open (fileCorrAnswer.c_str());
    // Checks if student answer file can be opened or not
    if(inSFile.fail())
    {
        // Displays error message
        cout<<"File "<<"\""<<fileStuAns<<"\""<< " could not be opened"<<endl;
        return;
    }// End of if condition
     // Checks if file can be opened or not
    if(inCFile.fail())
    {
        // Displays error message
        cout<<"File "<<"\""<<fileCorrAnswer<<"\""<< " could not be opened";
        return;
    }// End of if condition
     // Loops till end of the student answer file
    while(!inSFile.eof())
    {
        // Reads data from file and stores student answer character array's counter      index position
        inSFile>>sAns[counter];
        // Increase the current line counter by one
        counter++;
    }// End of while
     //Close student answer file
    inSFile.close();
    // Reset the counter to zero
    counter = 0;
    // Loops till end of correct answer the file
    while(!inCFile.eof())
    {
        // Reads data from file and stores correct answer character array's counter      index position
        inCFile>>cAns[counter];
        // Increase the current line counter by one
        counter++;
    }// End of while

     // Close correct answer file
    inCFile.close();
}// End of function

// Displays the student result
// First Parameter: Character type array contains student answers
// Second Parameter: Character type array contains correct answers
void resultSheet(char sAns[], char cAns[])
{
    // Displays student answers
}// End of function

// Function to write data to file entered by the user
// First Parameter: Invalid Answer file
// Second Parameter: Character type array contains student answers
// Third Parameter: Character type array contains correct answers
void writeTextFile(string fileInAnschar, char sAns[], char cAns[])
{
    // To store number of lines
    int cA, iA;
    cA = iA = 0;
    // ofstream class object created
    ofstream outFile;
    // Opens the file for writing onto a text file
    outFile.open(fileInAnschar.c_str());
    // Checks if file can be opened or not
    if(outFile.fail())
    {
        // Displays error message
        cout<<"\n Error: Unable to open "<<fileInAnschar;
        return;
    }// End of if condition
     // Loops till 20 times for 20 questions

    for(int c = 0; c < 20; c++)
    {
        // If student answers current index position value is not equals to correct      answer's current index position
        if(sAns[c] != cAns[c])
        {
            // Writes the result to the file
            outFile<<"Question "<<(c + 1)<<" has incorrect answer "<<"'"<<sAns[c]<<"'" <<", the correct answer is "<<"'"<<cAns[c]<<"'"<<endl;
            // Displays the result
            cout<<"Question "<<(c+1)<<" has incorrect answer "<<"'"<<sAns[c]<<"'"<<",      the correct answer is "<<"'"<<cAns[c]<<"'"<<endl;
            // Increase the counter by one
            iA++;
        }// End of if condition
    }// End of for loop
     // Calculates number of correct answers
    cA = 20 - iA;
    // Calculates the average
    double percent = cA / 20;
    // Checks if the average is greater than or equals 70
    if(iA <= 6)
    {
        // Displays the result
        cout<<iA<<" questions were missed"<<endl;
        cout<<"The student passed"<<endl;
    }// End of if condition
     // Otherwise fail
    else
    {
        cout<<iA<<" questions were missed"<<endl;
        cout<<"The student failed"<<endl;
    }// End of else
     //Close file
    outFile.close();
}//End of function

// main function definition
int main()
{
    // Character array to store student answers
    char studentAnswer[21];
    // Character array to store correct answers
    char correctAnswer[21];
    // To store the file name
    string fileNameStu, fileNameCorr;
    // Accepts the file name to read

    cin>>fileNameStu;

    cin>>fileNameCorr;
    // Calls the file to read student answer and correct answer and stores it in respective arrays
    readFile(fileNameStu, fileNameCorr, studentAnswer, correctAnswer);
    // Calls the function to display student answer and correct answer
    resultSheet(studentAnswer, correctAnswer);
    // Accepts the file name to write invalid answers

    cin>>fileNameStu;
    // Calls the function to write invalid answers
    writeTextFile(fileNameStu, studentAnswer, correctAnswer);
}// End of main function

My output:

File "invalidfile.txt" could not be opened

b"Question 1 has incorrect answer '\xf0', the correct answer is '\x00'\nQuestion 2 has incorrect answer ';', the correct answer is '\x00'\nQuestion 3 has incorrect answer '\xae', the correct answer is '\x00'\nQuestion 4 has incorrect answer '\xa7', the correct answer is '\x00'\nQuestion 5 has incorrect answer '\xff', the correct answer is '\x00'\nQuestion 6 has incorrect answer '\x7f', the correct answer is '\x00'\n"Question 9 has incorrect answer 'T', the correct answer is ''
Question 10 has incorrect answer '', the correct answer is ''
Question 11 has incorrect answer '@', the correct answer is ''
Question 17 has incorrect answer '', the correct answer is 'p'
Question 18 has incorrect answer '', the correct answer is ''
Question 19 has incorrect answer '', the correct answer is '@'

12 questions were missed

The student failed

Output should be:

File "invalidfile.txt" could not be opened

Attached picture of output:

Body:
A good way to do this is to use the exit command that is in cstdlib.
Basically anytime you throw an error also call exit. For example

std::cout << "Fatal error: Invalid file" << std::endl;
std::exit(1);

exit will terminate the program and by passing the '1' argument, it will terminate "unsuccessfully"


问:
Enable CORS for Subdomain ('www'), not just Domain
When I try to POST my contact form I receive a console error that my Lambda, SES, API Gateway, Cloudfront alternate origin configuration won't work from the subdomain 'www.example.com', while it works from 'example.com'. How can I allow the contact form to avoid any issues on multiple (sub)domains? The error in console tells me the following:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/rest/contact. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

My alternate Cloudfront origin catches '/rest/contact'. I've tested the Lambda function with API Gateway and SES - that works well. I've also enabled OPTIONS and CORS on API Gateway, which dismissed an earlier error. Using a wildcard on Route53, etc., hasn't done me any good either.

Any help is appreciated. I'm looking for a suggestion as to how to make my contact form as flexible as possible using these AWS services.

答: You can use Lambda function to generate the CORS headers dynamically based the origin header you get from the request if you don't want to have * as the value of the Access-Control-Allow-Origin


问:
Retain backslash in regex in 'gsub'
I want to replace spaces and forward slashes with an underscore, and retain backslashes.

How do I do this?

I have the following regex:

```<code>"hello\h /123".gsub(/[\s+\/]/, "_")
#=> "helloh__123"
</code>```

But it also replaces backslashes in the string.

答:
So, if you just want to convert space and slash with underscore, you might prefer:

```<code>"hello\h /123".tr('/ ','__') # 2nd arg is two underscores
#=> "helloh__123"
</code>```

(But I agree with the comments on the question so far.)

Title: Retain backslash in regex in 'gsub'

Body:
I want to replace spaces and forward slashes with an underscore, and retain backslashes.

How do I do this?

I have the following regex:

"hello\h /123".gsub(/[\s+\/]/, "_")
#=> "helloh__123"

But it also replaces backslashes in the string.

Body:
So, if you just want to convert space and slash with underscore, you might prefer:

"hello\h /123".tr('/ ','__') # 2nd arg is two underscores
#=> "helloh__123"

(But I agree with the comments on the question so far.)


问:
How do I calculate the date six months from the current date using the datetime Python module?
I am using the datetime Python module.  I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?

The reason I want to generate a date 6 months from the current date is to produce a review date.  If the user enters data into the system it will have a review date of 6 months from the date they entered the data.

答:
General function to get next date after/before x months.</p>

```
from datetime import date

def after_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12
    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = after_month(today, mm)
        print(next_date)
```

OwnerDisplayName: Eef

LastEditorDisplayName: Eef

Body:
General function to get next date after/before x months.

from datetime import date

def after_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12
    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today = date.today()
    print(today)

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = after_month(today, mm)
        print(next_date)


问:
C++ subclassing access modifier?
I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++.

I saw this C++ code:

```<code>    class World : public State
    {
    };
</code>```

It seems class World inherits the class State publicly.
Public subclassing? It's hard to understand.

What's the concept of this feature?
And when is this useful or required?

答:
What makes you think that it's private? It says public right there, which means it is publically subclassing.

That aside, what private and protected inheritance do is the same as public inheritance, except that all the member variables are functions are inherited with at least private or protected accessibility. For example, if State had a public member function 'foo()', it would be private in 'World'.

This is rarely used in practice, but it does have purpose. The most common use that I've seen is composition through inheritance. i.e. you want a "has a" relationship rather than an "is a" (that you usually get with public inheritance). By privately inheriting the class, you get all its variables and methods, but you don't expose them to the outside world.

One advantage of using private inheritance for composition comes from the empty base class optimisation (EBCO). Using normal composition, having a member object of an empty class would still use at least 1 byte because all variables must have a unique address. If you privately inherit the object you want to be composed of then that doesn't apply and you won't suffer memory loss.

e.g.

```<code>class Empty { };

class Foo
{
    int foo;
    Empty e;
};

class Bar : private Empty
{
    int foo;
};
</code>```

Here, sizeof(Foo) will probably be 5, but sizeof(Bar) will be 4 because of the empty base class.

Title: C++ subclassing access modifier?

Body:
I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++.

I saw this C++ code:

    class World : public State
    {
    };

It seems class World inherits the class State publicly.
Public subclassing? It's hard to understand.

What's the concept of this feature?
And when is this useful or required?

Body:
What makes you think that it's private? It says public right there, which means it is publically subclassing.

That aside, what private and protected inheritance do is the same as public inheritance, except that all the member variables are functions are inherited with at least private or protected accessibility. For example, if State had a public member function 'foo()', it would be private in 'World'.

This is rarely used in practice, but it does have purpose. The most common use that I've seen is composition through inheritance. i.e. you want a "has a" relationship rather than an "is a" (that you usually get with public inheritance). By privately inheriting the class, you get all its variables and methods, but you don't expose them to the outside world.

One advantage of using private inheritance for composition comes from the empty base class optimisation (EBCO). Using normal composition, having a member object of an empty class would still use at least 1 byte because all variables must have a unique address. If you privately inherit the object you want to be composed of then that doesn't apply and you won't suffer memory loss.

e.g.

class Empty { };

class Foo
{
    int foo;
    Empty e;
};

class Bar : private Empty
{
    int foo;
};

Here, sizeof(Foo) will probably be 5, but sizeof(Bar) will be 4 because of the empty base class.


问:
Password reset for Azure database
I have a new Azure account. I am able to log into the 'manage' page as admin, but I forgot the password to one of my databases. I would like to reset the password on that one DB. How do I do that? Microsoft doesn't seem to have a KB on that - at least not one I could find. Thx.</p>

答:
With the current iteration of the interface, the process is similar to what is described above with an additional step:

Get to the Overview as described above.

New: Click on the server name (I just had to stumble into it. Horrible UI design.)

Now there is an option to reset the password.

Title: Password reset for Azure database


问:
How to stop a GraphicsPath from closing
I'm trying to make an eraser tool that can erase points from a GraphicsPath. So far, my code lets the user paint on the form, and the "Erase" button is supposed to erase the first 20 points of the GraphicsPath. It works until two distinguishable drawings are made then the "Erase" button is pushed - as seen in the images, the two drawings connect. I suspect that the GraphicsPath closes itself (connecting each point).

Is there a way to prevent the GraphicsPath from connecting each point?

Here is my full code. I think the most relevant part is the function at the bottom.

```<code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;

namespace Cartographer
{
    public partial class testform : Form
    {

        private GraphicsPath _drawingPath = new GraphicsPath();
        private Point lastMouseLocation;
        private bool drawing = false;

        public testform()
        {
            InitializeComponent();
        }

        private void testform_Load(object sender, EventArgs e)
        {
            this.Paint += Testform_Paint;
            this.MouseMove += Testform_MouseMove;

            this.DoubleBuffered = true;
        }

        private void Testform_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                drawing = true;
                _drawingPath.AddLine(lastMouseLocation, e.Location);
                Invalidate();
            }

            if (e.Button == MouseButtons.None && drawing)
            {
                drawing = false;
                _drawingPath.StartFigure(); // problem is not due to this line

            }
            lastMouseLocation = e.Location;
        }

        private void Testform_Paint(object sender, PaintEventArgs e)
        {

            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            using (SolidBrush b = new SolidBrush(Color.Blue))
            using (Pen p = new Pen(b, 51))
            {
                p.StartCap = System.Drawing.Drawing2D.LineCap.Round;
                p.EndCap = System.Drawing.Drawing2D.LineCap.Round;
                p.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;

                e.Graphics.DrawPath(p, _drawingPath);

            }

            using (SolidBrush b = new SolidBrush(Color.LightGreen))
            using (Pen p = new Pen(b, 50))
            {
                p.StartCap = System.Drawing.Drawing2D.LineCap.Round;
                p.EndCap = System.Drawing.Drawing2D.LineCap.Round;
                p.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;

                e.Graphics.DrawPath(p, _drawingPath);
            }

        }

        private void btnErase_Click(object sender, EventArgs e)
        {
            List<PointF> ptsList = new List<PointF>();
            for (int i = 0; i < 20; i++)
            {
                ptsList.Add(_drawingPath.PathData.Points[i]);
            }

            _drawingPath = ErasePointsFromPath(_drawingPath, ptsList.ToArray<PointF>());
            this.Invalidate();
        }

        private GraphicsPath ErasePointsFromPath(GraphicsPath path, PointF[] toRemove)
        {
            PointF[] newPoints = path.PathData.Points.Except<PointF>(toRemove).ToArray<PointF>();
            byte[] types = new byte[newPoints.Length];
            for (int i = 0; i < newPoints.Length; i++)
            {
                types[i] = 1;
            }

            GraphicsPath ret = new GraphicsPath(newPoints, types);
            //ret.SetMarkers();
            return ret;
        }
    }
}
</code>```

This is what happens. The two round-ish lines in the drawing are supposed to be separate and not connected by that diagonal one.

答:
When you erase the points from the path you are doing so by copying them to a new path, excluding the ones you want to erase.  But you are not also copying the corresponding point type information from the first path; instead you are resetting all the point types to 1, for whatever reason.  This loses the information about where each figure within the path starts.  So what happens is the new path sees one long connected figure, which explains what you are seeing.

If you want to erase the first n points from the path, you might try something like this instead:

```<code>private void btnErase_Click(object sender, EventArgs e)
{
    int numberOfPointsToErase = 20;

    if (_drawingPath.PointCount > numberOfPointsToErase)
    {
        _drawingPath = new GraphicsPath(
            _drawingPath.PathPoints.Skip(numberOfPointsToErase).ToArray(),
            _drawingPath.PathTypes.Skip(numberOfPointsToErase).ToArray()
        );
    }
    else
    {
        _drawingPath.Reset();
    }

    this.Invalidate();
}
</code>```

Title: How to stop a GraphicsPath from closing

Body:
I'm trying to make an eraser tool that can erase points from a GraphicsPath. So far, my code lets the user paint on the form, and the "Erase" button is supposed to erase the first 20 points of the GraphicsPath. It works until two distinguishable drawings are made then the "Erase" button is pushed - as seen in the images, the two drawings connect. I suspect that the GraphicsPath closes itself (connecting each point).

Is there a way to prevent the GraphicsPath from connecting each point?

Here is my full code. I think the most relevant part is the function at the bottom.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;

namespace Cartographer
{
    public partial class testform : Form
    {

        private GraphicsPath _drawingPath = new GraphicsPath();
        private Point lastMouseLocation;
        private bool drawing = false;

        public testform()
        {
            InitializeComponent();
        }

        private void testform_Load(object sender, EventArgs e)
        {
            this.Paint += Testform_Paint;
            this.MouseMove += Testform_MouseMove;

            this.DoubleBuffered = true;
        }

        private void Testform_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                drawing = true;
                _drawingPath.AddLine(lastMouseLocation, e.Location);
                Invalidate();
            }

            if (e.Button == MouseButtons.None && drawing)
            {
                drawing = false;
                _drawingPath.StartFigure(); // problem is not due to this line

            }
            lastMouseLocation = e.Location;
        }

        private void Testform_Paint(object sender, PaintEventArgs e)
        {

            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            using (SolidBrush b = new SolidBrush(Color.Blue))
            using (Pen p = new Pen(b, 51))
            {
                p.StartCap = System.Drawing.Drawing2D.LineCap.Round;
                p.EndCap = System.Drawing.Drawing2D.LineCap.Round;
                p.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;

                e.Graphics.DrawPath(p, _drawingPath);

            }

            using (SolidBrush b = new SolidBrush(Color.LightGreen))
            using (Pen p = new Pen(b, 50))
            {
                p.StartCap = System.Drawing.Drawing2D.LineCap.Round;
                p.EndCap = System.Drawing.Drawing2D.LineCap.Round;
                p.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;

                e.Graphics.DrawPath(p, _drawingPath);
            }

        }

        private void btnErase_Click(object sender, EventArgs e)
        {
            List<PointF> ptsList = new List<PointF>();
            for (int i = 0; i < 20; i++)
            {
                ptsList.Add(_drawingPath.PathData.Points[i]);
            }

            _drawingPath = ErasePointsFromPath(_drawingPath, ptsList.ToArray<PointF>());
            this.Invalidate();
        }

        private GraphicsPath ErasePointsFromPath(GraphicsPath path, PointF[] toRemove)
        {
            PointF[] newPoints = path.PathData.Points.Except<PointF>(toRemove).ToArray<PointF>();
            byte[] types = new byte[newPoints.Length];
            for (int i = 0; i < newPoints.Length; i++)
            {
                types[i] = 1;
            }

            GraphicsPath ret = new GraphicsPath(newPoints, types);
            //ret.SetMarkers();
            return ret;
        }
    }
}

This is what happens. The two round-ish lines in the drawing are supposed to be separate and not connected by that diagonal one.

Body:
When you erase the points from the path you are doing so by copying them to a new path, excluding the ones you want to erase.  But you are not also copying the corresponding point type information from the first path; instead you are resetting all the point types to 1, for whatever reason.  This loses the information about where each figure within the path starts.  So what happens is the new path sees one long connected figure, which explains what you are seeing.

If you want to erase the first n points from the path, you might try something like this instead:

private void btnErase_Click(object sender, EventArgs e)
{
    int numberOfPointsToErase = 20;

    if (_drawingPath.PointCount > numberOfPointsToErase)
    {
        _drawingPath = new GraphicsPath(
            _drawingPath.PathPoints.Skip(numberOfPointsToErase).ToArray(),
            _drawingPath.PathTypes.Skip(numberOfPointsToErase).ToArray()
        );
    }
    else
    {
        _drawingPath.Reset();
    }

    this.Invalidate();
}


问:
Flink Logging getting job name or job id
I am trying to setup logback.xml so that it will include the JobName or JobId that the logging is associated with.

I have not yet been able to find a way to do this. Is it possible?

Ultimately what I'm wanting to achieve is the ability to have the logs shipped out to ElasticSearch and have the JobName or Id tagged with the message so I'm able to filter by job.

答:
We ended up doing the following, which felt super hacky and we wished we could find a better way.

Setup your cluster to use logback

Create a custom logback ContextSelector by implementing ch.qos.logback.classic.selector.ContextSelector

Place your jar in each of your Flink TaskManagers classpath

Modify FLINK_ENV_JAVA_OPTS_JM on each of your flink TaskManagers to specify your context selector. eg:

export FLINK_ENV_JAVA_OPTS_JM="-Dlogback.ContextSelector=your.custom.context.Selector"

Restart all of your task managers

Test it.

Here is a gist of the ContextSelector we created. I'd love pull requests for improvements if you have any!! Custom Flink Logback ContextSelector

This creates a LoggerContext for each JobID, and then makes a request to the JobManager using the JobID to get back the JobName. It then splits the JobName by ":" and puts the head component into a LoggerContext Property "flink_job_name" and puts the tail component into a LoggerContext Property "flink_job_version".


问:
Bash Shell Scripting: How to Sum the Values in a File With the Use of For Loop and bc Command
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

```<code>12
4
53
19
6
</code>```

So here's what I have so far:

```<code>function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}
</code>```

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

答:
While awk (or other higher level language: perl, python, etc) would be better suited for this task, you are on the right track for doing it the naive way. Tip:

```<code>$ x=1
$ y=$(bc <<<"$x + 1")
$ echo $y
2
</code>```

Body:
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

12
4
53
19
6

So here's what I have so far:

function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

Body:
While awk (or other higher level language: perl, python, etc) would be better suited for this task, you are on the right track for doing it the naive way. Tip:

$ x=1
$ y=$(bc <<<"$x + 1")
$ echo $y
2


问:
spark outer join with source
I am relatively new to spark, I was wondering if I could get the source of the column which was used for outer join

Let's say I have 3 DF

DF 1

```<code>+-----+----+
|item1| key|
+-----+----+
|Item1|key1|
|Item2|key2|
|Item3|key3|
|Item4|key4|
|Item5|key5|
+-----+----+
</code>```

DF2

```<code>+-----+----+
|item2| key|
+-----+----+
|   t1|key1|
|   t2|key2|
|   t3|key6|
|   t4|key7|
|   t5|key8|
+-----+----+
</code>```

DF3

```<code>+-----+-----+
|item3|  key|
+-----+-----+
|   t1| key1|
|   t2| key2|
|   t3| key8|
|   t4| key9|
|   t5|key10|
+-----+-----+
</code>```

I want to do full outer join on these 3 dataframes and include a new column with to indicate the source of that key.

E.g

```<code>+-----+-----+-----+-----+------+
|  key|item1|item2|item3|source|
+-----+-----+-----+-----+------+
| key8| null|   t5|   t3|   DF2|
| key5|Item5| null| null|   DF1|
| key7| null|   t4| null|   DF2|
| key3|Item3| null| null|   DF1|
| key6| null|   t3| null|   DF2|
| key1|Item1|   t1|   t1|   DF1|
| key4|Item4| null| null|   DF1|
| key2|Item2|   t2|   t2|   DF1|
| key9| null| null|   t4|   DF3|
|key10| null| null|   t5|   DF3|
+-----+-----+-----+-----+------+
</code>```

Is there any way to achieve this ?

答:
I'd do something like this:

```<code>from pyspark.sql.functions import col, lit, coalesce, when

df1 = spark.createDataFrame(
    [("Item1", "key1"), ("Item2", "key2"), ("Item3", "key3"),
    ("Item4", "key4"), ("Item5", "key5")],
    ["item1", "key"])

df2 = spark.createDataFrame(
    [("t1", "key1"), ("t2", "key2"), ("t3", "key6"),
    ("t4", "key7"), ("t5", "key8")],
    ["item2", "key"])

df3 = spark.createDataFrame([
    ("t1", "key1"), ("t2", "key2"), ("t3", "key8"),
    ("t4", "key9"), ("t5", "key10")],
    ["item3", "key"])

df1.join(df2, ["key"], "outer").join(df3, ["key"], "outer").withColumn(
    "source",
    coalesce(
        when(col("item1").isNotNull(), "df1"),
        when(col("item2").isNotNull(), "df2"),
        when(col("item3").isNotNull(), "df3")))
</code>```

Result is:

```<code>## +-----+-----+-----+-----+------+
## |  key|item1|item2|item3|source|
## +-----+-----+-----+-----+------+
## | key8| null|   t5|   t3|   df2|
## | key5|Item5| null| null|   df1|
## | key7| null|   t4| null|   df2|
## | key3|Item3| null| null|   df1|
## | key6| null|   t3| null|   df2|
## | key1|Item1|   t1|   t1|   df1|
## | key4|Item4| null| null|   df1|
## | key2|Item2|   t2|   t2|   df1|
## | key9| null| null|   t4|   df3|
## |key10| null| null|   t5|   df3|
## +-----+-----+-----+-----+------+
</code>```

Title: spark outer join with source

Body:
I am relatively new to spark, I was wondering if I could get the source of the column which was used for outer join

Let's say I have 3 DF

DF 1

+-----+----+
|item1| key|
+-----+----+
|Item1|key1|
|Item2|key2|
|Item3|key3|
|Item4|key4|
|Item5|key5|
+-----+----+

DF2

+-----+----+
|item2| key|
+-----+----+
|   t1|key1|
|   t2|key2|
|   t3|key6|
|   t4|key7|
|   t5|key8|
+-----+----+

DF3

+-----+-----+
|item3|  key|
+-----+-----+
|   t1| key1|
|   t2| key2|
|   t3| key8|
|   t4| key9|
|   t5|key10|
+-----+-----+

I want to do full outer join on these 3 dataframes and include a new column with to indicate the source of that key.

E.g

+-----+-----+-----+-----+------+
|  key|item1|item2|item3|source|
+-----+-----+-----+-----+------+
| key8| null|   t5|   t3|   DF2|
| key5|Item5| null| null|   DF1|
| key7| null|   t4| null|   DF2|
| key3|Item3| null| null|   DF1|
| key6| null|   t3| null|   DF2|
| key1|Item1|   t1|   t1|   DF1|
| key4|Item4| null| null|   DF1|
| key2|Item2|   t2|   t2|   DF1|
| key9| null| null|   t4|   DF3|
|key10| null| null|   t5|   DF3|
+-----+-----+-----+-----+------+

Is there any way to achieve this ?

Body:
I'd do something like this:

from pyspark.sql.functions import col, lit, coalesce, when

df1 = spark.createDataFrame(
    [("Item1", "key1"), ("Item2", "key2"), ("Item3", "key3"),
    ("Item4", "key4"), ("Item5", "key5")],
    ["item1", "key"])

df2 = spark.createDataFrame(
    [("t1", "key1"), ("t2", "key2"), ("t3", "key6"),
    ("t4", "key7"), ("t5", "key8")],
    ["item2", "key"])

df3 = spark.createDataFrame([
    ("t1", "key1"), ("t2", "key2"), ("t3", "key8"),
    ("t4", "key9"), ("t5", "key10")],
    ["item3", "key"])

df1.join(df2, ["key"], "outer").join(df3, ["key"], "outer").withColumn(
    "source",
    coalesce(
        when(col("item1").isNotNull(), "df1"),
        when(col("item2").isNotNull(), "df2"),
        when(col("item3").isNotNull(), "df3")))

Result is:

## +-----+-----+-----+-----+------+
## |  key|item1|item2|item3|source|
## +-----+-----+-----+-----+------+
## | key8| null|   t5|   t3|   df2|
## | key5|Item5| null| null|   df1|
## | key7| null|   t4| null|   df2|
## | key3|Item3| null| null|   df1|
## | key6| null|   t3| null|   df2|
## | key1|Item1|   t1|   t1|   df1|
## | key4|Item4| null| null|   df1|
## | key2|Item2|   t2|   t2|   df1|
## | key9| null| null|   t4|   df3|
## |key10| null| null|   t5|   df3|
## +-----+-----+-----+-----+------+


问:
Sending mail via php script using wamp server
I am using WAMP server 2.4. I want to send a mail to my gmail account. The code I used for the  same is given below. I read some forums and they suggested me to make changes in php.ini file.But it is not a permanent solution.Also some suggested that mail() does not work for gmail ? Is there some solution to this? </p>

```<code>       <?php
      //Checking if entries are ok
      if(isset($_POST['submit']))
      {

         if(isset($_POST['username']))
         $id = $_POST['username'];

         else
         echo "Cannot be blank";

         //ensuring mail goes to registered user
         $query="SELECT * FROM table1 WHERE id = '$id' ";
         $result= mysql_query($query,$con);

         if (!($result) )
         {
            die('Error: ' . mysql_error($con));
         }

         else
         {

              $values = mysql_fetch_array($result);
         }

       // Sending mail...
         if(mysql_num_rows($result)== 1)
         {
          if(isset($_POST['email']))
          $to= $_POST['email'];
              else
              echo "invalid email";
              $msg = 'Name :' .$values['name'] ."\n"
                    .'Id:' .$values['id']."\n"
                    .'Email:' .$values['email']."\n"
          ."Your password is:" . $values[password];

            mail($to,"Forget your Password",$msg);
            header('location: sent_mail.php');

    }
        else
        echo "Verify your username again";
}
    else{
    echo "sending failed";
    header('location: forget_password.php');
    exit(0);
}
</code>```

答:
Folks. After many hours of trying I found that: You don't need additional tools like mailservers or pear additions. These only provide additional potential security leaks that you have no control or insight over. To get mail function to work on localhost, all you need to do is change the php.ini file. I just checked my outlook account settings and copied those to the php.ini file. So SMTP server, port, username and password.

Now, You may think it does not work but You should know that many mail clients reject emails if the From field has a different domain than the actual domain an email is received from. So if the php.ini file contains for example smtp.ziggo.nl Be sure that the header contains: From: info@ziggo.nl

So for making universal code on both localhost and remote host, I check for the existence of a file that I only have locally (e.g. z_local) and set the headers accordingly. If the local file does not exist I must be on the remote ISP and choose the header "From: info@remotesite.com"

Body:
I am using WAMP server 2.4. I want to send a mail to my gmail account. The code I used for the  same is given below. I read some forums and they suggested me to make changes in php.ini file.But it is not a permanent solution.Also some suggested that mail() does not work for gmail ? Is there some solution to this?

       <?php
      //Checking if entries are ok
      if(isset($_POST['submit']))
      {

         if(isset($_POST['username']))
         $id = $_POST['username'];

         else
         echo "Cannot be blank";

         //ensuring mail goes to registered user
         $query="SELECT * FROM table1 WHERE id = '$id' ";
         $result= mysql_query($query,$con);

         if (!($result) )
         {
            die('Error: ' . mysql_error($con));
         }

         else
         {

              $values = mysql_fetch_array($result);
         }

       // Sending mail...
         if(mysql_num_rows($result)== 1)
         {
          if(isset($_POST['email']))
          $to= $_POST['email'];
              else
              echo "invalid email";
              $msg = 'Name :' .$values['name'] ."\n"
                    .'Id:' .$values['id']."\n"
                    .'Email:' .$values['email']."\n"
          ."Your password is:" . $values[password];

            mail($to,"Forget your Password",$msg);
            header('location: sent_mail.php');

    }
        else
        echo "Verify your username again";
}
    else{
    echo "sending failed";
    header('location: forget_password.php');
    exit(0);
}


问:
creating a heatmap where the data has NaN values in it
I am trying to create a heatmap using the heatmap.2 package. My data has lot's of NaN values in it, and what I would like to do is the following. Every time there is a NaN value, simply have the cell be colored as light grey (or some other neutral color, maybe white), and all of the other values (which are log2 expression) to have a standard green/yellow/red coloring scheme. Here is my code that I have ben using:

```<code>heatmap.2(as.matrix(foo2[rowSums (abs(foo2)) != 0,]),
          col = redgreen,
          margins = c(12, 22),
          trace = "none",
          xlab = "Comparison",
          lhei = c(2, 8),
          scale = c("none"),
          symbreaks = min(foo2 = 0, na.rm = TRUE),
          na.color = "blue",
          cexRow = 0.5,
          cexCol = .7,
          main = "DE geness",
          Colv = F)
</code>```

This works well when there is no NaN values, but when the data has NaN, I am getting an error which says:

```<code>Error in hclustfun(distfun(x)) :
  NA/NaN/Inf in foreign function call (arg 11)
</code>```

Essentially, I would like to have it ignore the NaN's in the data. I am not sure how to handle this. any help would be greatly appreciated.

答:
So I am not an expert in coding at all, but I have been learning to make heatmaps on R and I kept having the same error message for my NA data. It turns out the reason I was getting the error message was there were NA terms in the first column in my data and R did not like that at all. So I added an extra column and filled it with 1's and it worked!!
I hope maybe someone will find this useful!

Kahina

Body:
I am trying to create a heatmap using the heatmap.2 package. My data has lot's of NaN values in it, and what I would like to do is the following. Every time there is a NaN value, simply have the cell be colored as light grey (or some other neutral color, maybe white), and all of the other values (which are log2 expression) to have a standard green/yellow/red coloring scheme. Here is my code that I have ben using:

heatmap.2(as.matrix(foo2[rowSums (abs(foo2)) != 0,]),
          col = redgreen,
          margins = c(12, 22),
          trace = "none",
          xlab = "Comparison",
          lhei = c(2, 8),
          scale = c("none"),
          symbreaks = min(foo2 = 0, na.rm = TRUE),
          na.color = "blue",
          cexRow = 0.5,
          cexCol = .7,
          main = "DE geness",
          Colv = F)

This works well when there is no NaN values, but when the data has NaN, I am getting an error which says:

Error in hclustfun(distfun(x)) :
  NA/NaN/Inf in foreign function call (arg 11)

Essentially, I would like to have it ignore the NaN's in the data. I am not sure how to handle this. any help would be greatly appreciated.


答:
This old question hasn't got a proper answer so far. Here is a concise data.table solution using the rleid() function:

```<code>library(data.table)
setDT(signal)[order(Date), .(Start = first(Date)), by = .(rleid(Sig), Sig)][
  , Stop := shift(Start, type = "lead")][
    -.N, !"rleid"]
</code>```

```<code>    Sig      Start       Stop
1:   Go 2012-03-25 2012-04-15
2: Stop 2012-04-15 2012-06-24
3:   Go 2012-06-24 2012-10-14
4: Stop 2012-10-14 2012-12-02
5:   Go 2012-12-02 2012-12-16
</code>```

Explanation

setDT()coerces signal to class data.table. Then signal is ordered by Date and aggregated by continuous streaks of Sig using rleid() and by the value of Sig. The first row of each group is picked. To determine the stop dates the new Start column is shifted forward. Finally, the last row and the rleid grouping variable are removed.

Data

OP's data:

```<code>library(data.table)
signal <- fread(
  " i          Date Sig
1  2012-03-25  Go
2  2012-04-15 Stop
3  2012-04-22 Stop
4  2012-05-13 Stop
5  2012-05-20 Stop
6  2012-06-24  Go
7  2012-09-23  Go
8  2012-09-30  Go
9  2012-10-14 Stop
10 2012-12-02  Go
11 2012-12-16 Stop", drop = 1L, data.table = FALSE
)
</code>```

Title: Merging date ranges in R

Body:
I have this dataframe (called signal):

         Date Sig
1  2012-03-25  Go
2  2012-04-15 Stop
3  2012-04-22 Stop
4  2012-05-13 Stop
5  2012-05-20 Stop
6  2012-06-24  Go
7  2012-09-23  Go
8  2012-09-30  Go
9  2012-10-14 Stop
10 2012-12-02  Go
11 2012-12-16 Stop

And I am trying to merge/join the date ranges in order to create something like that:

        Start        Stop Sig
1  2012-03-25  2012-04-15 Go
2  2012-04-15  2012-06-24 Stop
3  2012-06-24  2012-10-14 Go
4  2012-10-14  2012-12-02 Stop
5  2012-12-12  2012-12-16 Go

Any ideas, please?

Body:
This old question hasn't got a proper answer so far. Here is a concise data.table solution using the rleid() function:

library(data.table)
setDT(signal)[order(Date), .(Start = first(Date)), by = .(rleid(Sig), Sig)][
  , Stop := shift(Start, type = "lead")][
    -.N, !"rleid"]

    Sig      Start       Stop
1:   Go 2012-03-25 2012-04-15
2: Stop 2012-04-15 2012-06-24
3:   Go 2012-06-24 2012-10-14
4: Stop 2012-10-14 2012-12-02
5:   Go 2012-12-02 2012-12-16

Explanation

setDT()coerces signal to class data.table. Then signal is ordered by Date and aggregated by continuous streaks of Sig using rleid() and by the value of Sig. The first row of each group is picked. To determine the stop dates the new Start column is shifted forward. Finally, the last row and the rleid grouping variable are removed.

Data

OP's data:

library(data.table)
signal <- fread(
  " i          Date Sig
1  2012-03-25  Go
2  2012-04-15 Stop
3  2012-04-22 Stop
4  2012-05-13 Stop
5  2012-05-20 Stop
6  2012-06-24  Go
7  2012-09-23  Go
8  2012-09-30  Go
9  2012-10-14 Stop
10 2012-12-02  Go
11 2012-12-16 Stop", drop = 1L, data.table = FALSE
)