问:
Why does't this draw an orbit and just draws an ellipse?
I started to create a very rough simulation of a solar system using p5.js, inspired by Daniel Shiffman's video.

I tried to draw the orbit for every planet by saving the positions where the planet was in an array, then using a for loop to iterate through them and draw a circle at every saved position.

Except it doesn't work!

It should have worked because to be sure that it was the best way to do that I searched and got in another of Daniel Shiffman's videos, and apparently it worked for him but unfortunately not for me!

Could someone please tell me what's the problem with what I'm doing. (Sorry for my poor English)

Down here there's the code in a snippet!

class Planet
{
    constructor(orbitCenter, color, mass, velocityLimit)
    {
        this.orbitCenter = orbitCenter;
        this.color = color;
        this.mass = mass;
        this.velocityLimit = velocityLimit;

        this.position = createVector(width/2, 50);
        this.radius = 15;
        this.velocity = createVector(30, 10);
        this.acceleration = createVector(0.0, 0.0);
        this.pathPoints = [];
    }

    render()
    {
        const diameter = this.radius * 2;
        ellipseMode(CENTER);
        noStroke();
        fill(this.color);
        ellipse(this.position.x, this.position.y, diameter);

        if(this.pathPoints.length > 1000)
        {
            this.pathPoints.splice(0, 1);
        }

        for(let i = 0; i < this.pathPoints.length; i++)
        {
            let pos = this.pathPoints[i];
            fill(255);
            ellipse(pos.x, pos.y, 5, 5);
        }
    }

    update()
    {
        this.position.add(this.velocity);
        this.velocity.add(this.acceleration);
        this.acceleration = createVector(this.orbitCenter.x, this.orbitCenter.y)
            .sub(this.position)
            .mult(this.mass);
        this.velocity.limit(this.velocityLimit);
        this.pathPoints.push(this.position);
    }
}

class Star
{
    constructor(color, position, diameter)
    {
        this.color = color;
        this.position = position;
        this.diameter = diameter;
    }

    render()
    {
        fill(this.color);
        noStroke();
        ellipse(this.position.x, this.position.y, this.diameter);
    }
}

let sun;
let earth, mars;
let sunDiameter = 40;

function setup()
{
    createCanvas(windowWidth, windowHeight);
    frameRate(60);

    let sunPos = createVector(width/2, height/2);
    sun = new Star(color(255, 255, 0), sunPos, sunDiameter);

    earth = new Planet(sunPos, color(0, 100, 255), 0.0008, 4.5);
    mars = new Planet(sunPos, color(255, 100, 0), 0.0004, 5);
}

let toggleOrbit = true;
function draw()
{
    background(0);
    sun.render();

    earth.render();
    mars.render();

    if(toggleOrbit)
    {
        earth.update();
        mars.update();
    }

}

function windowResized()
{
    resizeCanvas(windowWidth, windowHeight);
    setup();
}

function keyPressed(e)
{
    if(e.key == ' ')
    {
        toggleOrbit = !toggleOrbit;
    }

    if(e.key == 'c')
    {
        console.log(earth.getPathPoints());
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Gravity Simulation</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>

        <style>
            *
            {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body
            {
                width: 100vw;
                height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        </style>
    </head>
    <body>
        <script src="main.js"></script>
    </body>
</html></code>```

答:
When you write this.pathPoints.push(this.position) you end up storing a reference to the object this.position rather than its X and Y values, so when it comes the time of drawing the orbit it uses the current value of this.position every time. If, instead, you store the X and Y values you'll get the result you want; replace

```<code>this.pathPoints.push(this.position);
</code>```

for

```<code>this.pathPoints.push({
    x: this.position.x,
    y: this.position.y
})
</code>```

and you'll see the orbit being drawn.

class Planet
{
    constructor(orbitCenter, color, mass, velocityLimit)
    {
        this.orbitCenter = orbitCenter;
        this.color = color;
        this.mass = mass;
        this.velocityLimit = velocityLimit;

        this.position = createVector(width/2, 50);
        this.radius = 15;
        this.velocity = createVector(30, 10);
        this.acceleration = createVector(0.0, 0.0);
        this.pathPoints = [];
    }

    render()
    {
        const diameter = this.radius * 2;
        ellipseMode(CENTER);
        noStroke();
        fill(this.color);
        ellipse(this.position.x, this.position.y, diameter);

        if(this.pathPoints.length > 1000)
        {
            this.pathPoints.splice(0, 1);
        }

        for(let i = 0; i < this.pathPoints.length; i++)
        {
            let pos = this.pathPoints[i];
            fill(255);
            ellipse(pos.x, pos.y, 5, 5);
        }
    }

    update()
    {
        this.position.add(this.velocity);
        this.velocity.add(this.acceleration);
        this.acceleration = createVector(this.orbitCenter.x, this.orbitCenter.y)
            .sub(this.position)
            .mult(this.mass);
        this.velocity.limit(this.velocityLimit);
        this.pathPoints.push({
            x: this.position.x,
            y: this.position.y
        })
    }
}

class Star
{
    constructor(color, position, diameter)
    {
        this.color = color;
        this.position = position;
        this.diameter = diameter;
    }

    render()
    {
        fill(this.color);
        noStroke();
        ellipse(this.position.x, this.position.y, this.diameter);
    }
}

let sun;
let earth, mars;
let sunDiameter = 40;

function setup()
{
    createCanvas(windowWidth, windowHeight);
    frameRate(60);

    let sunPos = createVector(width/2, height/2);
    sun = new Star(color(255, 255, 0), sunPos, sunDiameter);

    earth = new Planet(sunPos, color(0, 100, 255), 0.0008, 4.5);
    mars = new Planet(sunPos, color(255, 100, 0), 0.0004, 5);
}

let toggleOrbit = true;
function draw()
{
    background(0);
    sun.render();

    earth.render();
    mars.render();

    if(toggleOrbit)
    {
        earth.update();
        mars.update();
    }

}

function windowResized()
{
    resizeCanvas(windowWidth, windowHeight);
    setup();
}

function keyPressed(e)
{
    if(e.key == ' ')
    {
        toggleOrbit = !toggleOrbit;
    }

    if(e.key == 'c')
    {
        console.log(earth.getPathPoints());
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Gravity Simulation</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>

        <style>
            *
            {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body
            {
                width: 100vw;
                height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        </style>
    </head>
    <body>
        <script src="main.js"></script>
    </body>
</html></code>```

Body:
I started to create a very rough simulation of a solar system using p5.js, inspired by Daniel Shiffman's video.

I tried to draw the orbit for every planet by saving the positions where the planet was in an array, then using a for loop to iterate through them and draw a circle at every saved position.

Except it doesn't work!

It should have worked because to be sure that it was the best way to do that I searched and got in another of Daniel Shiffman's videos, and apparently it worked for him but unfortunately not for me!

Could someone please tell me what's the problem with what I'm doing. (Sorry for my poor English)

Down here there's the code in a snippet!

class Planet
{
    constructor(orbitCenter, color, mass, velocityLimit)
    {
        this.orbitCenter = orbitCenter;
        this.color = color;
        this.mass = mass;
        this.velocityLimit = velocityLimit;

        this.position = createVector(width/2, 50);
        this.radius = 15;
        this.velocity = createVector(30, 10);
        this.acceleration = createVector(0.0, 0.0);
        this.pathPoints = [];
    }

    render()
    {
        const diameter = this.radius * 2;
        ellipseMode(CENTER);
        noStroke();
        fill(this.color);
        ellipse(this.position.x, this.position.y, diameter);

        if(this.pathPoints.length > 1000)
        {
            this.pathPoints.splice(0, 1);
        }

        for(let i = 0; i < this.pathPoints.length; i++)
        {
            let pos = this.pathPoints[i];
            fill(255);
            ellipse(pos.x, pos.y, 5, 5);
        }
    }

    update()
    {
        this.position.add(this.velocity);
        this.velocity.add(this.acceleration);
        this.acceleration = createVector(this.orbitCenter.x, this.orbitCenter.y)
            .sub(this.position)
            .mult(this.mass);
        this.velocity.limit(this.velocityLimit);
        this.pathPoints.push(this.position);
    }
}

class Star
{
    constructor(color, position, diameter)
    {
        this.color = color;
        this.position = position;
        this.diameter = diameter;
    }

    render()
    {
        fill(this.color);
        noStroke();
        ellipse(this.position.x, this.position.y, this.diameter);
    }
}

let sun;
let earth, mars;
let sunDiameter = 40;

function setup()
{
    createCanvas(windowWidth, windowHeight);
    frameRate(60);

    let sunPos = createVector(width/2, height/2);
    sun = new Star(color(255, 255, 0), sunPos, sunDiameter);

    earth = new Planet(sunPos, color(0, 100, 255), 0.0008, 4.5);
    mars = new Planet(sunPos, color(255, 100, 0), 0.0004, 5);
}

let toggleOrbit = true;
function draw()
{
    background(0);
    sun.render();

    earth.render();
    mars.render();

    if(toggleOrbit)
    {
        earth.update();
        mars.update();
    }

}

function windowResized()
{
    resizeCanvas(windowWidth, windowHeight);
    setup();
}

function keyPressed(e)
{
    if(e.key == ' ')
    {
        toggleOrbit = !toggleOrbit;
    }

    if(e.key == 'c')
    {
        console.log(earth.getPathPoints());
    }
}

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Gravity Simulation</title>

Body:
When you write this.pathPoints.push(this.position) you end up storing a reference to the object this.position rather than its X and Y values, so when it comes the time of drawing the orbit it uses the current value of this.position every time. If, instead, you store the X and Y values you'll get the result you want; replace

this.pathPoints.push(this.position);

for

this.pathPoints.push({
    x: this.position.x,
    y: this.position.y
})

and you'll see the orbit being drawn.

class Planet
{
    constructor(orbitCenter, color, mass, velocityLimit)
    {
        this.orbitCenter = orbitCenter;
        this.color = color;
        this.mass = mass;
        this.velocityLimit = velocityLimit;

        this.position = createVector(width/2, 50);
        this.radius = 15;
        this.velocity = createVector(30, 10);
        this.acceleration = createVector(0.0, 0.0);
        this.pathPoints = [];
    }

    render()
    {
        const diameter = this.radius * 2;
        ellipseMode(CENTER);
        noStroke();
        fill(this.color);
        ellipse(this.position.x, this.position.y, diameter);

        if(this.pathPoints.length > 1000)
        {
            this.pathPoints.splice(0, 1);
        }

        for(let i = 0; i < this.pathPoints.length; i++)
        {
            let pos = this.pathPoints[i];
            fill(255);
            ellipse(pos.x, pos.y, 5, 5);
        }
    }

    update()
    {
        this.position.add(this.velocity);
        this.velocity.add(this.acceleration);
        this.acceleration = createVector(this.orbitCenter.x, this.orbitCenter.y)
            .sub(this.position)
            .mult(this.mass);
        this.velocity.limit(this.velocityLimit);
        this.pathPoints.push({
            x: this.position.x,
            y: this.position.y
        })
    }
}

class Star
{
    constructor(color, position, diameter)
    {
        this.color = color;
        this.position = position;
        this.diameter = diameter;
    }

    render()
    {
        fill(this.color);
        noStroke();
        ellipse(this.position.x, this.position.y, this.diameter);
    }
}

let sun;
let earth, mars;
let sunDiameter = 40;

function setup()
{
    createCanvas(windowWidth, windowHeight);
    frameRate(60);

    let sunPos = createVector(width/2, height/2);
    sun = new Star(color(255, 255, 0), sunPos, sunDiameter);

    earth = new Planet(sunPos, color(0, 100, 255), 0.0008, 4.5);
    mars = new Planet(sunPos, color(255, 100, 0), 0.0004, 5);
}

let toggleOrbit = true;
function draw()
{
    background(0);
    sun.render();

    earth.render();
    mars.render();

    if(toggleOrbit)
    {
        earth.update();
        mars.update();
    }

}

function windowResized()
{
    resizeCanvas(windowWidth, windowHeight);
    setup();
}

function keyPressed(e)
{
    if(e.key == ' ')
    {
        toggleOrbit = !toggleOrbit;
    }

    if(e.key == 'c')
    {
        console.log(earth.getPathPoints());
    }
}

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Gravity Simulation</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.sound.min.js"></script>

        <style>
            *
            {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body
            {
                width: 100vw;
                height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        </style>
    </head>
    <body>
        <script src="main.js"></script>
    </body>
</html>


来源: stackexchange

问:
How to check for the existence of values after splitting in object, and then assign them if only the last one does not exist
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

```<code>for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/
</code>```

that is, each scroll is added as long as i is less than the length of the array
it should work like this

```<code>obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};
</code>```

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5

答:
I have found the answer. You can change path and comment var obj = {}. First, if you want to create a1 in obj you have to change path to a1. The script will check the path and create it in obj. After that. You can add /b1 to a1 to create b1 in a1 and etc.

If you make a mistake in the path (var obj = {} and var path = 'a1/b1/c1'.split("/");) the program will output the error.
console.log("Wrong path_2"); - (here) b1 - is not found.
 console.log("Wrong path_1"); - (here) a1 - is not found.

In this script I have var obj = {} and path = ["a1","b1"]. obj doesn't have a1 so console will output 'Wrong path_1' and our obj

var path = 'a1/b1'.split("/");
var obj = {};
var addition = "";
var elem_name = "";
for(elem of path){
    if(obj[elem] === undefined && path.length === 1){

        obj[elem] = {};
        console.log(`${elem} have been created`);

    }else if(obj[elem] !== undefined && path.length > 1){

        obj = obj;
        addition = obj[elem];
        elem_name = elem;

    }else if(addition[elem] === undefined && path.length > 1 && addition !== ""){
        if(elem === path[path.length-1]){

            addition[elem] = {};
            console.log(`${elem} have been created in ${elem_name}`);
            break;

        }else if(elem !== path[path.length-1]){
            console.log("Wrong path_2");
            break;
        }

    }else if(addition[elem] !== undefined && path.length >1){

        obj = obj;
        addition = addition[elem];
        elem_name = elem;
        console.log(`${elem} was created earlier`);

    }else if(obj[elem] === undefined && path.length > 1){
        console.log(`Wrong path_1`);
        break;

    }else if(obj[elem] !== undefined && path.length === 1){
        console.log(`${elem} was created earlier`);
        break;

    }
}
console.log(obj);```

ContentLicense: CC BY-SA 4.0

Body:
There is a question about sorting and adding an object, more precisely for example:

I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you

for(var i = 0; i < spl.length(); i++){
    // and here's the code I don't know how to write
}

/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};

//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};

//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};

//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};

/if the last element of the massiv is existing then do nothing
the end of the cycle*/

that is, each scroll is added as long as i is less than the length of the array
it should work like this

obj {
    a1:{
        b1:{
            c1:{
                d1:{}
            }
        }
    }
};

For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5


问:
Error while using string.Format for strings with newline chars
Getting error while using string.Format

errorMessage is "OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@title='Client nc.']"}"

code:

```<code>errorMessage = (exceptions.CurrentDotNetExceptionMessage.ToString() + "\n" + exceptions.CurrentDotNetInnerException.ToString().Split(new[] { '\r', '\n' }).FirstOrDefault()) ?? string.Empty;

 defectDetails = string.Format($"Issue: {actualResult} \n\n" +
                $"Steps To Reproduce: \n {stepsToReproduce} \n\n" +
                $"Failed Step: \n {failedStep} \n" +
                $"Failed Element: \n {failedElement} \n" +
                $"Test Data: \n {testData} \n\n" +
                $"Actual Result: \n {actualResult} \n" +
                $"Expected Result: \n {expectedResult} \n" +
                $"Error Message: \n {errorMessage.ToString()} \n\n" +
                $"Browser: {browser} \n" +
                $"Enviornment: {environment}\n\n" +
                $"Stack Trace: {stackTrace}" +
                $"\n---------------------------------------------------------------------------------------------------\n\n"
                );```
Error Line:
```string.Format($"Error Message: \n {errorMessage} \n");```

Error: string.FormatException
```

答: My bad: Used string.Format along with interpolation. Worked when removed string.Format</p>

Body:
Getting error while using string.Format

errorMessage is "OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@title='Client nc.']"}"

code:

errorMessage = (exceptions.CurrentDotNetExceptionMessage.ToString() + "\n" + exceptions.CurrentDotNetInnerException.ToString().Split(new[] { '\r', '\n' }).FirstOrDefault()) ?? string.Empty;

 defectDetails = string.Format($"Issue: {actualResult} \n\n" +
                $"Steps To Reproduce: \n {stepsToReproduce} \n\n" +
                $"Failed Step: \n {failedStep} \n" +
                $"Failed Element: \n {failedElement} \n" +
                $"Test Data: \n {testData} \n\n" +
                $"Actual Result: \n {actualResult} \n" +
                $"Expected Result: \n {expectedResult} \n" +
                $"Error Message: \n {errorMessage.ToString()} \n\n" +
                $"Browser: {browser} \n" +
                $"Enviornment: {environment}\n\n" +
                $"Stack Trace: {stackTrace}" +
                $"\n---------------------------------------------------------------------------------------------------\n\n"
                );```
Error Line:
```string.Format($"Error Message: \n {errorMessage} \n");```

Error: string.FormatException


问:
How can I build a Swift Package for iOS over command line?
In Xcode, I can select my destination as a "generic iOS device" or any iOS simulator, and my package will build platform-specific code for ios.

Via command line "swift build" only builds my target for macOS.

I want to build the target for iOS for CI purposes. The problem with building for macOS is that UIKit-specific code won't be built.

For example:

```<code>#if canImport(UIKit)
    // some invalid code
#endif
</code>```

The invalid code will not be noticed and will pass the build phase.

Ideally, I could say something like swift build -platform iOS. Is there a way to do something like this?

答:
At time of writing (Feb 16, 2019), a working solution is:

```<code>swift build -v \
    -Xswiftc "-sdk" \
    -Xswiftc "`xcrun --sdk iphonesimulator --show-sdk-path`" \
    -Xswiftc "-target" \
    -Xswiftc "x86_64-apple-ios13.0-simulator"
</code>```

This command uses -Xswiftc to workaround the issue by overriding the sdk from macOS to iphonesimulator.

Strictly we add these flags so developers can work around issues, but they also should report a bug so that we can provide a proper solution for their needs.

Source

So I'm guessing there will be a more elegant solution in the future.

Body:
In Xcode, I can select my destination as a "generic iOS device" or any iOS simulator, and my package will build platform-specific code for ios.

Via command line "swift build" only builds my target for macOS.

I want to build the target for iOS for CI purposes. The problem with building for macOS is that UIKit-specific code won't be built.

For example:

#if canImport(UIKit)
    // some invalid code
#endif

The invalid code will not be noticed and will pass the build phase.

Ideally, I could say something like swift build -platform iOS. Is there a way to do something like this?

Body:
At time of writing (Feb 16, 2019), a working solution is:

swift build -v \
    -Xswiftc "-sdk" \
    -Xswiftc "`xcrun --sdk iphonesimulator --show-sdk-path`" \
    -Xswiftc "-target" \
    -Xswiftc "x86_64-apple-ios13.0-simulator"

This command uses -Xswiftc to workaround the issue by overriding the sdk from macOS to iphonesimulator.

Strictly we add these flags so developers can work around issues, but they also should report a bug so that we can provide a proper solution for their needs.

Source

So I'm guessing there will be a more elegant solution in the future.


问:
Get parent element of nested child by class or name
I have html elements like follows with unknown hierarchy:

          Nested Child 1

```

<pre class="lang-html prettyprint-override"><code><div class="parent" name="parent">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>
</code>```

Is there any easy way to get parent of nested child by class or name?

Maybe there is some alternative to child.parentElement or child.parentNode I am not aware of which may help me?

Or looping through all parents until I get needed class or name is the only possible choice?

答:
You can use node.closest() with polyfill if you need.

function get_parent (node, selector) {
  console.log(node.closest(selector));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent" name="parent">
  <div>
    <div>
      <div>
        <div onclick="get_parent(this, '.parent')">
          Nested Child 1
        </div>
      </div>
    </div>
  </div>
</div>

<div class="other-parent" name="other-parent">
  <div>
    <div onclick="get_parent(this, '.other-parent')">
      Nested Child 2
    </div>
  </div>
</div></code>```

Body:
I have html elements like follows with unknown hierarchy:

          Nested Child 1

      Nested Child 2

Is there any easy way to get parent of nested child by class or name?

Maybe there is some alternative to child.parentElement or child.parentNode I am not aware of which may help me?

Or looping through all parents until I get needed class or name is the only possible choice?

Body:
You can use node.closest() with polyfill if you need.

function get_parent (node, selector) {
  console.log(node.closest(selector));
}

<div class="parent" name="parent">
  <div>
    <div>
      <div>
        <div onclick="get_parent(this, '.parent')">
          Nested Child 1
        </div>
      </div>
    </div>
  </div>
</div>

<div class="other-parent" name="other-parent">
  <div>
    <div onclick="get_parent(this, '.other-parent')">
      Nested Child 2
    </div>
  </div>
</div>


问:
List<T>.Remove does not remove Object
I am implementing the following code to remove an item from a list

```<code>// RemoveRole is a member function in a class for Person
// roles is defined as
// List<PersonOrganisationRoleModel> roles;
// And properly populated prior to this function call

public void RemoveRole(string RoleName)
{
    // I am creating an object that needs to be matched in the list
    PersonOrganisationRoleModel role = new PersonOrganisationRoleModel(OrganisationID, PersonID, RoleName)

    // "role" is now properly constructed, and is matching an exact copy of one of the objects in "roles"
    // the expectation now is the the object "role" must be matched with one of the objects in "roles",
    // and that one be removed
    roles.Remove(role);

}
</code>```

But the "Remove" function call on the "roles" list does not remove the item in the list that contains the exact same values.

My understanding is that this is supposed to work (it is just the inverse of List.Add

答:
The reason is that your role object is not a member of the list and has a different address on memory. By the way if you override Equals method ,like above , you are able to use that. You can also remove via LINQ like this example.

```<code>roles.RemoveAll(r => r.OrganisationID == OrganisationID && r.PersonID == PersonID)
</code>```

This remove all objects in the list by this OrganisationID and PersonID.

Title: List<T>.Remove does not remove Object

Body:
I am implementing the following code to remove an item from a list

// RemoveRole is a member function in a class for Person
// roles is defined as
// List<PersonOrganisationRoleModel> roles;
// And properly populated prior to this function call

public void RemoveRole(string RoleName)
{
    // I am creating an object that needs to be matched in the list
    PersonOrganisationRoleModel role = new PersonOrganisationRoleModel(OrganisationID, PersonID, RoleName)

    // "role" is now properly constructed, and is matching an exact copy of one of the objects in "roles"
    // the expectation now is the the object "role" must be matched with one of the objects in "roles",
    // and that one be removed
    roles.Remove(role);

}

But the "Remove" function call on the "roles" list does not remove the item in the list that contains the exact same values.

My understanding is that this is supposed to work (it is just the inverse of List.Add

Body:
The reason is that your role object is not a member of the list and has a different address on memory. By the way if you override Equals method ,like above , you are able to use that. You can also remove via LINQ like this example.

roles.RemoveAll(r => r.OrganisationID == OrganisationID && r.PersonID == PersonID)

This remove all objects in the list by this OrganisationID and PersonID.


问:
how to check if directory exists with Storage:: facade in laravel?
What is the counterpart of:

```<code>if (!File::exists($path))
</code>```

using Storage:: in Laravel 5.1 ?

Anyone?

答:
```<code>   if(!Storage::disk('ads')->exists(auth()->user()->id)) {
        Storage::disk('ads')->makeDirectory(auth()->user()->id, 0775, true); //creates directory
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What is the counterpart of:

if (!File::exists($path))

using Storage:: in Laravel 5.1 ?

Anyone?


问:
Laravel get user id in unprotected route
I am using Laravel guard to to protect routes, now I want to get user id in unprotected (common) routes, for example:

Protected:

/Profile

Unprotected:

/Search

I able to get user id in protected routes, for example ProfileController.php, like this:

```<code>$id = auth()->guard('agent')->user()->id;
</code>```

But I want to get this in searchController.php but it return null, any idea?

api.php:

```<code>Route::middleware('auth:agent')->group(function () {
    Route::get('profile', 'ProfileController@details');
});

Route::post('search', 'searchController@search');
</code>```

In other hand, when user is logged, and open search page, I want to get user id.

答:
You should create a controller that pass user data such id or etc:

```<code>Route::middleware('auth:agent')->group(function () {
    Route::get('userdata', 'ProfileController@userdata'); // return user id
});
</code>```

And:

```<code>public function userdata(){
   ...
   $id = auth()->guard('agent')->user()->id; // just id
   return $id;
}
</code>```

This controller can fetch all user data, now you should need to call this request in your search controller:

```<code>app('App\Http\Controllers\ProfileController')->userdata();
</code>```

Body:
I am using Laravel guard to to protect routes, now I want to get user id in unprotected (common) routes, for example:

Protected:

/Profile

Unprotected:

/Search

I able to get user id in protected routes, for example ProfileController.php, like this:

$id = auth()->guard('agent')->user()->id;

But I want to get this in searchController.php but it return null, any idea?

api.php:

Route::middleware('auth:agent')->group(function () {
    Route::get('profile', 'ProfileController@details');
});

Route::post('search', 'searchController@search');

In other hand, when user is logged, and open search page, I want to get user id.

Body:
You should create a controller that pass user data such id or etc:

Route::middleware('auth:agent')->group(function () {
    Route::get('userdata', 'ProfileController@userdata'); // return user id
});

And:

public function userdata(){
   ...
   $id = auth()->guard('agent')->user()->id; // just id
   return $id;
}

This controller can fetch all user data, now you should need to call this request in your search controller:

app('App\Http\Controllers\ProfileController')->userdata();


答:
I think closest is the best solution.

function get_parent(elem) {
/*** For Class ***/
 // var x = elem.closest(".parent").className;
 /*** For Name ***/
   var x = elem.closest(".parent").attributes["name"].value;
  document.getElementById("demo").innerHTML = x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent" name="parent1">
<div>
  <div>
    <div>
      <div onclick="get_parent(this)">
        Nested Child 1
      </div>
    </div>
  </div>
</div>
</div>
<div class="parent" name="parent2">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>

<p id="demo"></p></code>```

Title: Get parent element of nested child by class or name

Body:
I think closest is the best solution.

function get_parent(elem) {
/*** For Class ***/
 // var x = elem.closest(".parent").className;
 /*** For Name ***/
   var x = elem.closest(".parent").attributes["name"].value;
  document.getElementById("demo").innerHTML = x;
}

<div class="parent" name="parent1">
<div>
  <div>
    <div>
      <div onclick="get_parent(this)">
        Nested Child 1
      </div>
    </div>
  </div>
</div>
</div>
<div class="parent" name="parent2">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>

<p id="demo"></p>


问:
Semantic HTML: Which is the heading, which is the sub-heading?
I have a situation where I will have a lot of content that has a heading in small text, and directly below it will be a longer heading (sometimes even a sentence) in much larger text, followed by the standard paragraph text. Here is an example of what I'm talking about:

body {
  font-family: Arial, sans-serif;
  max-width: 400px;
  margin: 0 auto;
}
h2 {
  font-size: 12px;
  text-transform: uppercase;
  margin: 20px 0 10px;
}
.tagline {
  margin: 0 0 20px 0;
  font-size: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Section Title</h2>
<p class="tagline">A tagline... Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque.</p>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quos dolorem delectus neque est quidem numquam, incidunt corporis temporibus alias fuga.</p></code>```

My initial instinct is to make the first part the heading element via
 and make the second section into a paragraph (as you can see in my example). But would this be correct? The larger text is definitely what people will most likely read first, but the smaller text is a better title for the section.

My question is am I good with this or should I swap it and make the small text a paragraph and the large text the heading tag?

In addition, I'm wondering if I should also be wrapping these two "headings" into a  tag as well?

答:
Why not use hierarchy of headings? In your example, if tag line is a heading you should put that behind h3.

Screen readers don’t present CSS to users so ask yourself, “does the content ‘structure’ still make sense when css is reduced?” If you use proper semantics then the structure will be preserved but with mocking styles (like heading style applied to a p tag) will lose its meaning when CSS is removed. Meaning screen readers would just present the tag line as paragraph text vs. presenting it as a sub heading. People navigate or jump through headings using screen readers so p tag tag line will not be in their heading navigation.

Does that make sense? Happy to clarify anything confusing.

Body:
I have a situation where I will have a lot of content that has a heading in small text, and directly below it will be a longer heading (sometimes even a sentence) in much larger text, followed by the standard paragraph text. Here is an example of what I'm talking about:

body {
  font-family: Arial, sans-serif;
  max-width: 400px;
  margin: 0 auto;
}
h2 {
  font-size: 12px;
  text-transform: uppercase;
  margin: 20px 0 10px;
}
.tagline {
  margin: 0 0 20px 0;
  font-size: 24px;
}

Section Title

A tagline... Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quos dolorem delectus neque est quidem numquam, incidunt corporis temporibus alias fuga.

My initial instinct is to make the first part the heading element via
 and make the second section into a paragraph (as you can see in my example). But would this be correct? The larger text is definitely what people will most likely read first, but the smaller text is a better title for the section.

My question is am I good with this or should I swap it and make the small text a paragraph and the large text the heading tag?

In addition, I'm wondering if I should also be wrapping these two "headings" into a  tag as well?


问:
Alternative to the HTML Bold tag
Okay, so I know that in HTML you can use the  tag, but isn't there a "weight=bold" attribute that I can use in the
 tag?

Or is that in CSS, or Javascript?

答:
Maybe you want to use CSS classes?

```<code>p.bold { font-weight:bold; }
</code>```

That way you can still use
 as normal.

```<code><p>This is normal text</p>
<p class="bold">This is bold text</p>
</code>```

Gives you:

This is normal text.

This is Bold Text.

OwnerDisplayName: Learner

LastEditorDisplayName: Cerebrus

Title: Alternative to the HTML Bold tag

Body:
Maybe you want to use CSS classes?

p.bold { font-weight:bold; }

That way you can still use <p> as normal.

<p>This is normal text</p>
<p class="bold">This is bold text</p>

Gives you:

This is normal text.

This is Bold Text.


问:
Are there ways to delete custom record types from CloudKit Dashboard?
Some of the fields have been changed and I need to delete record types in the Dashboard and start over.
Screenshot of my dashboad

I need to delete all three record types: coordinates, cravingLog, and journalLog. I tried clicking on "Delete Record Type" button at the bottom, but I can't click it. It won't let me delete them.

I looked everywhere on the Dashboard for help, but I could not find any ways to delete them.

答:
You can only delete record types in the development schema, and only as long as the schema has not been deployed to production.

As soon as it has been deployed, deletion is no longer possible - even if the delete button is enabled. Pushing the button then gives an error message.

The only way to get rid of such record types is to use a new container. But containers that are no longer needed cannot be deleted either...


问:
Axios POST requests fail to use proxy
I'm currently testing out the endpoints on my server via a React client using Axios. I have a proxy (http://localhost:8080) set up in my package.JSON for my client. All my GET requests are successful. My POST requests on the other-hand all fail to make use of the proxy provided in package.JSON, instead, it's using (http://localhost:3000).

Please see code below

Login Component

```<code>function Login{

      const handleSubmit = (e) =>{
            e.preventDefault();

            let email = e.target.email.value;
            let password = e.target.password.value;

            axios.post("/user/login", {email:email, password:password})
           .then((res) => console.log(res))
           .catch((err) => console.log(err));
           }

      return(
       <div className="form login">
        <h1>Login</h1>

        <form onSubmit={handleSubmit}>
            <input type="email" placeholder="Email" name="email"/>
            <input type="password" placeholder="Password" name="password"/>
            <input type="submit"/>
        </form>
        </div>
       );
}
</code>```

This is the solution I tried after my original attempt failed

Previous handleSubmit()

```<code>const handleSubmit = (e) =>{

      try{
            let res = await axios({
                method: "post",
                url: "/user/login",
                data: {},
                proxy:{
                    host: "localhost",
                    port: "8080"
                }
            })

            console.log(res);

        }
        catch(err){
            console.log(err)
        }

}
</code>```

This solution also seems to direct requests to http://localhost:3000

Package.JSON

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8080",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

</code>```

Any ideas as to how I can remedy this?
Thanks for any and all suggestions.

答:
XMLHttpRequest doesn't provide an API to set a proxy server, so the config option isn't used with the xhr adaptor. It is only supported by the http adaptor which is used when you run Axios under Node.js.

If you want to use a traditional proxy server, you need to manually change the configuration of the browser (or the OS if the browser picks it up from there).

Title: Axios POST requests fail to use proxy

Body:
I'm currently testing out the endpoints on my server via a React client using Axios. I have a proxy (http://localhost:8080) set up in my package.JSON for my client. All my GET requests are successful. My POST requests on the other-hand all fail to make use of the proxy provided in package.JSON, instead, it's using (http://localhost:3000).

Please see code below

Login Component

function Login{

      const handleSubmit = (e) =>{
            e.preventDefault();

            let email = e.target.email.value;
            let password = e.target.password.value;

            axios.post("/user/login", {email:email, password:password})
           .then((res) => console.log(res))
           .catch((err) => console.log(err));
           }

      return(

Login

        <form onSubmit={handleSubmit}>
            <input type="email" placeholder="Email" name="email"/>
            <input type="password" placeholder="Password" name="password"/>
            <input type="submit"/>
        </form>

       );
}

This is the solution I tried after my original attempt failed

Previous handleSubmit()

const handleSubmit = (e) =>{

      try{
            let res = await axios({
                method: "post",
                url: "/user/login",
                data: {},
                proxy:{
                    host: "localhost",
                    port: "8080"
                }
            })

            console.log(res);

        }
        catch(err){
            console.log(err)
        }

}

This solution also seems to direct requests to http://localhost:3000

Package.JSON

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8080",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Any ideas as to how I can remedy this?
Thanks for any and all suggestions.


问:
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

```<code>size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);
</code>```

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

答:
Try something like the following, then use buffer wherever you need a char*. As Ben mentioned, you need to be very careful to keep the buffer larger than the string plus null terminator.

```<code>const int BUFFER_SIZE = 255;

string str ("Your string");
char buffer[BUFFER_SIZE];
if (str.length() < BUFFER_SIZE)
{
    size_t copy_length;
    copy_length=str.copy(buffer,str.length(),0);
    buffer[copy_length]='\0';
}
</code>```

Body:
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

Body:
Try something like the following, then use buffer wherever you need a char*. As Ben mentioned, you need to be very careful to keep the buffer larger than the string plus null terminator.

const int BUFFER_SIZE = 255;

string str ("Your string");
char buffer[BUFFER_SIZE];
if (str.length() < BUFFER_SIZE)
{
    size_t copy_length;
    copy_length=str.copy(buffer,str.length(),0);
    buffer[copy_length]='\0';
}


问:
volley return from inner class
I have successfully created a server to serve me API. As my server has many API and I want to use them on my android project, so I am writing a two method for my Android application.

One is for get, this method will handle all sort of GET requests.

```<code>public static JSONObject postData(final Context context, String path, Map data)
{

    final RequestQueue requstQueue = Volley.newRequestQueue(context);
    String url=Util.serverURL+path;

    JSONObject res=null;

    JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST,url ,new JSONObject(data),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                res=response;
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context,error.toString(),Toast.LENGTH_SHORT).show();
            }
        }
    ){

    };
    requstQueue.add(jsonobj);
}
</code>```

Here is the problem it can't return the response.

How can I return the response from inner class ?

Assigning the res gives me error. And how should I return so that using async I can receive that?

答:
You can't get response from asynchronous operation like this. You have to use callback function to get result when asynchronous operation complete. Follow below steps:

Create an interface for callback

```<code>interface VolleyResponseListener {
    void onComplete(JSONObject jsonbject);
}
</code>```

Configure your postData to handle this callback

```<code>public void postData(final Context context, String path, Map data, VolleyResponseListener callback) {

    ....
        @Override
        public void onResponse(JSONObject response) {
            callback.onComplete(response);
        }

    ....
}
</code>```

Implement this interface in your activity or fragment

```<code>postData(..., new VolleyResponseListener() {
    @Override
    public void onComplete(JSONObject jsonbject) {
        //you can use jsonbject here
    }
});
</code>```

Title: volley return from inner class

Body:
I have successfully created a server to serve me API. As my server has many API and I want to use them on my android project, so I am writing a two method for my Android application.

One is for get, this method will handle all sort of GET requests.

public static JSONObject postData(final Context context, String path, Map data)
{

    final RequestQueue requstQueue = Volley.newRequestQueue(context);
    String url=Util.serverURL+path;

    JSONObject res=null;

    JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST,url ,new JSONObject(data),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                res=response;
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context,error.toString(),Toast.LENGTH_SHORT).show();
            }
        }
    ){

    };
    requstQueue.add(jsonobj);
}

Here is the problem it can't return the response.

How can I return the response from inner class ?

Assigning the res gives me error. And how should I return so that using async I can receive that?

Body:
You can't get response from asynchronous operation like this. You have to use callback function to get result when asynchronous operation complete. Follow below steps:

Create an interface for callback

interface VolleyResponseListener {
    void onComplete(JSONObject jsonbject);
}

Configure your postData to handle this callback

public void postData(final Context context, String path, Map data, VolleyResponseListener callback) {

    ....
        @Override
        public void onResponse(JSONObject response) {
            callback.onComplete(response);
        }

    ....
}

Implement this interface in your activity or fragment

postData(..., new VolleyResponseListener() {
    @Override
    public void onComplete(JSONObject jsonbject) {
        //you can use jsonbject here
    }
});


问:
How to get curl/curl.h in curl?
I downloaded curl to use webdriverxx.

I compiled after insert, but there is about 70 error saying that cannot open the file curl/curl.h.

There is a header file called curl.h in the curl I downloaded, but there is no header file called curl/curl.h. So I searched Google, but I don't know where to get the file.

答:
Can you tell which OS are you using?

If you found the curl.h file in the https://github.com/sekogan/webdriverxx#unicode but don't see it in the file you have downloaded, try to copy the curl.h content from github, create another curl.h file in the correct path (/curl/ like you said) and paste the file content you have copied from to github to your curl.h file.

Some other things you can do:

Redownload the file (remember to delete clearly the old file)

Create an issue on the repository

Make sure that you have downloaded the file in the correct path and run it in the correct path

Remember again did you missing something (did you download it normally, is there any error appears when you were downloading it, have you read clearly the README.md file, there may be a download guide in that file, ...)

Title: How to get curl/curl.h in curl?


问:
Python filter rows with condition
Hi I have a datframe that look like this

```<code>        Date     Col1         Col2         Col3       col4
0     1-4-2020    a        ed kv sc        sf ds       n
1     1-4-2020    b        hed sf ed       df hed      c
2     1-4-2020    c        df xz sf        sf ds       n
3     2-4-2020    a        ed df hed       sf ds       n
4     2-4-2020    b        gv bb sc        s ds        c
5     2-4-2020    c        ed sf sc        hed ds      n
</code>```

What I want to do is to filter the rows  with multiple conditions.
If:

Tow rows have the same value in Col1. For example a == a

And they have the same values in Col4. n==n

If both conditions are true search Col2 and Col3 for the key strings "hed" and "sf". they can be in Col2 or Col3(or both)

So the result will look like this:

```<code>       Date     Col1         Col2         Col3       col4
1     1-4-2020    b        hed sf ed      df hed       c
3     2-4-2020    a        ed df hed      sf djs       n
5     2-4-2020    c        ed sf ssc      hed djs      n
</code>```

I hope it is clear
Update

In case Col4

```<code>        Date     Col1         Col2         Col3       col4
0     1-4-2020    a        ed kv sc        sf ds       n
1     1-4-2020    b        hed sf ed       df hed      c
2     1-4-2020    c        df xz sf        sf ds       n
3     1-4-2020    d        df xdg sf       sf hed      y
4     2-4-2020    a        ed df hed       sf ds       n
5     2-4-2020    b        gv bb sc        s ds        c
6     2-4-2020    c        ed sf sc        hed ds      n
7     2-4-2020    d        df xgfgf       gf gfd       null
</code>```

In case that the value in Col4 appears only once in the dataframe like in row 3 (hint no next row to compare with) the function should return the row.

```<code>        Date     Col1         Col2         Col3       col4
1     1-4-2020    b        hed sf ed       df hed      c
3     1-4-2020    d        df xdg sf       sf hed      y
4     2-4-2020    a        ed df hed       sf ds       n
6     2-4-2020    c        ed sf sc        hed ds      n
</code>```

答:
First get counts of rows by same Col1 and Col4 by GroupBy.transform with GroupBy.size and join column Col2 with Col3 toegether:

```<code>count = df.groupby(['Col1','col4'])['col4'].transform('size')
s = (df['Col2'] + ' ' + df['Col3'])
</code>```

You can verify output:

```<code>print (df.assign(count=count, both=s))
       Date Col1       Col2    Col3 col4  count              both
0  1-4-2020    a   ed kv sc   sf ds    n      2    ed kv sc sf ds
1  1-4-2020    b  hed sf ed  df hed    c      2  hed sf ed df hed
2  1-4-2020    c   df xz sf   sf ds    n      2    df xz sf sf ds
3  2-4-2020    a  ed df hed   sf ds    n      2   ed df hed sf ds
4  2-4-2020    b   gv bb sc    s ds    c      2     gv bb sc s ds
5  2-4-2020    c   ed gf sc  hed ds    n      2   ed gf sc hed ds
</code>```

Last filter by boolean indexing if counts are 2 by Series.eq, then Series.str.contains for test substrings and chained mask together by & for bitwise AND:

```<code>df = df[count.eq(2) & s.str.contains('hed') & s.str.contains('sf')]
print (df)
       Date Col1       Col2    Col3 col4
1  1-4-2020    b  hed sf ed  df hed    c
3  2-4-2020    a  ed df hed   sf ds    n
</code>```

Title: Python filter rows with condition

Body:
Hi I have a datframe that look like this

        Date     Col1         Col2         Col3       col4
0     1-4-2020    a        ed kv sc        sf ds       n
1     1-4-2020    b        hed sf ed       df hed      c
2     1-4-2020    c        df xz sf        sf ds       n
3     2-4-2020    a        ed df hed       sf ds       n
4     2-4-2020    b        gv bb sc        s ds        c
5     2-4-2020    c        ed sf sc        hed ds      n

What I want to do is to filter the rows  with multiple conditions.
If:

Tow rows have the same value in Col1. For example a == a

And they have the same values in Col4. n==n

If both conditions are true search Col2 and Col3 for the key strings "hed" and "sf". they can be in Col2 or Col3(or both)

So the result will look like this:

       Date     Col1         Col2         Col3       col4
1     1-4-2020    b        hed sf ed      df hed       c
3     2-4-2020    a        ed df hed      sf djs       n
5     2-4-2020    c        ed sf ssc      hed djs      n

I hope it is clear
Update

In case Col4

        Date     Col1         Col2         Col3       col4
0     1-4-2020    a        ed kv sc        sf ds       n
1     1-4-2020    b        hed sf ed       df hed      c
2     1-4-2020    c        df xz sf        sf ds       n
3     1-4-2020    d        df xdg sf       sf hed      y
4     2-4-2020    a        ed df hed       sf ds       n
5     2-4-2020    b        gv bb sc        s ds        c
6     2-4-2020    c        ed sf sc        hed ds      n
7     2-4-2020    d        df xgfgf       gf gfd       null

In case that the value in Col4 appears only once in the dataframe like in row 3 (hint no next row to compare with) the function should return the row.

        Date     Col1         Col2         Col3       col4
1     1-4-2020    b        hed sf ed       df hed      c
3     1-4-2020    d        df xdg sf       sf hed      y
4     2-4-2020    a        ed df hed       sf ds       n
6     2-4-2020    c        ed sf sc        hed ds      n

Body:
First get counts of rows by same Col1 and Col4 by GroupBy.transform with GroupBy.size and join column Col2 with Col3 toegether:

count = df.groupby(['Col1','col4'])['col4'].transform('size')
s = (df['Col2'] + ' ' + df['Col3'])

You can verify output:

print (df.assign(count=count, both=s))
       Date Col1       Col2    Col3 col4  count              both
0  1-4-2020    a   ed kv sc   sf ds    n      2    ed kv sc sf ds
1  1-4-2020    b  hed sf ed  df hed    c      2  hed sf ed df hed
2  1-4-2020    c   df xz sf   sf ds    n      2    df xz sf sf ds
3  2-4-2020    a  ed df hed   sf ds    n      2   ed df hed sf ds
4  2-4-2020    b   gv bb sc    s ds    c      2     gv bb sc s ds
5  2-4-2020    c   ed gf sc  hed ds    n      2   ed gf sc hed ds

Last filter by boolean indexing if counts are 2 by Series.eq, then Series.str.contains for test substrings and chained mask together by & for bitwise AND:

df = df[count.eq(2) & s.str.contains('hed') & s.str.contains('sf')]
print (df)
       Date Col1       Col2    Col3 col4
1  1-4-2020    b  hed sf ed  df hed    c
3  2-4-2020    a  ed df hed   sf ds    n


问:
Sort Multidimensional Array with Dynamic Key on Child Value - PHP
I have a 4 dimensional associative array, with all of its key dynamic. I want to sort the array on the value of its last child.
For a reference, this is the array:

```<code>$array = array(
    "Africa" => array(
        "Egypt" => array(
            "20" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        "Sudan" => array(
            "249" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        ...
        ...
    ),
    "Europe" => array(
        "Greece" => array(
            "30" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        "Netherlands" => array(
            "31" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        ...
        ...
    ),
    ...
    ...
);
</code>```

In the above array, I want to sort on the basis of population in descending order. So far, I've tried uasort, array_multisort, but I think I am doing it wrong. Can someone please help me sort this?

```<code>uasort($records[$continent][$country][$countryCode]['basicInfo'], array($this, 'sortByPopulation' ));
</code>```

To be clear, I am sorting it in the for loop while it is being created. Since all the variables inside the array are dynamic, I think it cannot be sorted after generating the array.

The final result should be in the same format as above, continents > countries > codes > basicInfo.

Thank You

答:
Assuming you want to sort within continents, this code will do what you want. It iterates over each continent within the array, using a custom sort function to sort on the population value for each country. To deal with the dynamic keys within the country, we use current to get the first element of the array, from which we can then get to basicInfo and then population:

```<code>$array = array_map(function ($arr) {
    uasort($arr, function ($a, $b) {
        return current($b)['basicInfo']['population'] - current($a)['basicInfo']['population'];
    });
    return $arr;
}, $array);
print_r($array);
</code>```

Demo on 3v4l.org

Note that it doesn't make any sense to sort while you are generating the array as you will still need to sort it after you insert the last value. So just run your loop and then sort...

Body:
I have a 4 dimensional associative array, with all of its key dynamic. I want to sort the array on the value of its last child.
For a reference, this is the array:

$array = array(
    "Africa" => array(
        "Egypt" => array(
            "20" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        "Sudan" => array(
            "249" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        ...
        ...
    ),
    "Europe" => array(
        "Greece" => array(
            "30" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        "Netherlands" => array(
            "31" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        ...
        ...
    ),
    ...
    ...
);

In the above array, I want to sort on the basis of population in descending order. So far, I've tried uasort, array_multisort, but I think I am doing it wrong. Can someone please help me sort this?

uasort($records[$continent][$country][$countryCode]['basicInfo'], array($this, 'sortByPopulation' ));

To be clear, I am sorting it in the for loop while it is being created. Since all the variables inside the array are dynamic, I think it cannot be sorted after generating the array.

The final result should be in the same format as above, continents > countries > codes > basicInfo.

Thank You

Body:
Assuming you want to sort within continents, this code will do what you want. It iterates over each continent within the array, using a custom sort function to sort on the population value for each country. To deal with the dynamic keys within the country, we use current to get the first element of the array, from which we can then get to basicInfo and then population:

$array = array_map(function ($arr) {
    uasort($arr, function ($a, $b) {
        return current($b)['basicInfo']['population'] - current($a)['basicInfo']['population'];
    });
    return $arr;
}, $array);
print_r($array);

Demo on 3v4l.org

Note that it doesn't make any sense to sort while you are generating the array as you will still need to sort it after you insert the last value. So just run your loop and then sort...


问:
How to fix the git repo if I accidentally create the repo with a submodule (sub repo) in it?
If I do the following:

```<code>mkdir TryReactHooks
cd TryReactHooks
npx create-react-app my-app
git init
git remote add origin git@gitlab.com:username/tryreacthooks.git  # optional
git add .
git commit -am "Initial Commit"
git push -u origin master
</code>```

then for some reason, this repo doesn't seem to track any file in the my-app folder.  It is probably due to my-app is a repo by itself (because create-react-app did it).  If I do

```<code>mv my-app/.git my-app/.git-tmp
</code>```

so that my-app is no longer a git repo, I find that still the current repo won't track any changes made to my-app even if I do git add .  How can this be fixed?

答:
I used some of those commands as an alias and didn't see one "hint" from git.

Turns out after you rename the my-app/.git to my-app/.git-tmp

Do a

```<code>git rm --cached my-app
</code>```

and now you can

```<code>git add .
git com -am "ok"
</code>```

and add all files to the repo.

The "hint" from git was:

```<code>hint: You've added another git repository inside your current repository.
hint: Clones of the outer repository will not contain the contents of
hint: the embedded repository and will not know how to obtain it.
hint: If you meant to add a submodule, use:
hint:
hint:   git submodule add <url> my-app
hint:
hint: If you added this path by mistake, you can remove it from the
hint: index with:
hint:
hint:   git rm --cached my-app
hint:
hint: See "git help submodule" for more information.
</code>```

Body:
If I do the following:

mkdir TryReactHooks
cd TryReactHooks
npx create-react-app my-app
git init
git remote add origin git@gitlab.com:username/tryreacthooks.git  # optional
git add .
git commit -am "Initial Commit"
git push -u origin master

then for some reason, this repo doesn't seem to track any file in the my-app folder.  It is probably due to my-app is a repo by itself (because create-react-app did it).  If I do

mv my-app/.git my-app/.git-tmp

so that my-app is no longer a git repo, I find that still the current repo won't track any changes made to my-app even if I do git add .  How can this be fixed?

Body:
I used some of those commands as an alias and didn't see one "hint" from git.

Turns out after you rename the my-app/.git to my-app/.git-tmp

Do a

git rm --cached my-app

and now you can

git add .
git com -am "ok"

and add all files to the repo.

The "hint" from git was:

hint: You've added another git repository inside your current repository.
hint: Clones of the outer repository will not contain the contents of
hint: the embedded repository and will not know how to obtain it.
hint: If you meant to add a submodule, use:
hint:
hint:   git submodule add <url> my-app
hint:
hint: If you added this path by mistake, you can remove it from the
hint: index with:
hint:
hint:   git rm --cached my-app
hint:
hint: See "git help submodule" for more information.


问:
Inserting indexed array into an database with PHP and MySqli
I'm trying to get an indexed array's values inserted into a SQL database with MySQLi and PHP but I can't figure out why it's not working.</p>

```<code>$con = mysqli_connect("localhost","user","pword","db");
if (mysqli_connect_errno()) {
   echo "Unable to connect to MySQL! ". mysqli_connect_error();
   exit();
}

$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
$stmt= $con->prepare($sqli);
$stmt->bindParam("ssss",$csv[0],$csv[1],$csv[2],$csv[3]);
$status = $stmt->execute();
if (!$status) {
    echo "Error ".$stmt->errorCode()."\nMessage ".implode($stmt->errorInfo())."\n";
    exit(1);
}
</code>```

答:
problem is at bindParam

```<code>$stmt->bindParam(1,$csv[0]);
$stmt->bindParam(2,$csv[1]);
$stmt->bindParam(3,$csv[2]);
$stmt->bindParam(4,$csv[3]);
</code>```

correct format is as above

also use try-catch

```<code>$con= new PDO("mysql:host=127.0.0.1;dbname=task", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$csv = array('test', 15, 'testing', 'noted');
$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";

$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$csv[0]);
$stmt->bindParam(2,$csv[1]);
$stmt->bindParam(3,$csv[2]);
$stmt->bindParam(4,$csv[3]);
$status = $stmt->execute();
if (!$stmt) {
    echo PDO::errorInfo();
}
</code>```

Body:
I'm trying to get an indexed array's values inserted into a SQL database with MySQLi and PHP but I can't figure out why it's not working.

$con = mysqli_connect("localhost","user","pword","db");
if (mysqli_connect_errno()) {
   echo "Unable to connect to MySQL! ". mysqli_connect_error();
   exit();
}

$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";
$stmt= $con->prepare($sqli);
$stmt->bindParam("ssss",$csv[0],$csv[1],$csv[2],$csv[3]);
$status = $stmt->execute();
if (!$status) {
    echo "Error ".$stmt->errorCode()."\nMessage ".implode($stmt->errorInfo())."\n";
    exit(1);
}

Body:
problem is at bindParam

$stmt->bindParam(1,$csv[0]);
$stmt->bindParam(2,$csv[1]);
$stmt->bindParam(3,$csv[2]);
$stmt->bindParam(4,$csv[3]);

correct format is as above

also use try-catch

$con= new PDO("mysql:host=127.0.0.1;dbname=task", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$csv = array('test', 15, 'testing', 'noted');
$sqli = "INSERT INTO path_info (path_name,operating_frequency,pi_description,pi_note) VALUES (?,?,?,?)";

$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$csv[0]);
$stmt->bindParam(2,$csv[1]);
$stmt->bindParam(3,$csv[2]);
$stmt->bindParam(4,$csv[3]);
$status = $stmt->execute();
if (!$stmt) {
    echo PDO::errorInfo();
}


问:
How do I limit the number of times a block is called?
In How do I limit the number of replacements when using gsub?, someone suggested the following way to do a limited number of substitutions:

```<code>str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"
</code>```

It works, but the code mixes up how many times to substitute (5) with what the substitution should be ("x" if there should be a substitution, $& otherwise). Is it possible to seperate the two out?

(If it's too hard to seperate the two things out in this scenario, but it can be done in some other scenarios, post that as an answer)

答:
gsub will call the block exactly as often as the regex matches the string. The only way to prevent that is to call break in the block, however that will also keep gsub from producing a meaningful return value.

So no, unless you call break in the block (which prevents any further code in the yielding method from running and thus prevents the method from returning anything), the number of times a method calls a block is solely determined by the method itself. So if you want gsub to yield only 5 times, the only way to do that is to pass in a regex which only matches the given strings five times.

Body:
In How do I limit the number of replacements when using gsub?, someone suggested the following way to do a limited number of substitutions:

str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"

It works, but the code mixes up how many times to substitute (5) with what the substitution should be ("x" if there should be a substitution, $& otherwise). Is it possible to seperate the two out?

(If it's too hard to seperate the two things out in this scenario, but it can be done in some other scenarios, post that as an answer)


问:
Formula not being calculated in Java Class Method
Java 11.6
I am new to Java and trying to create a BMI calculator that will take in Person's weight, height and calculate the BMI. The program takes in the data but does not show any answer for the BMI calculation. Since there are no errors, I am not sure if my algorithm is wrong or basic coding error.

The PersonWeight.java class

```<code>import java.time.Year;

public class PersonWeight {

    private double height;
    private double weight;

    public PersonWeight() {

        height = 0;
        weight = 0;

    }

    public PersonWeight(double h, double w) {

        height = h;
        weight = w;

    }

    public void setHeight(double h) {
        this.height = h;
    }

    public double getHeight() {
        return height;
    }

    public void setWeight(double w) {
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    public double ComputeBMI() {

        double bmi = ((weight)/(height*height));
        return bmi;
    }

}
</code>```

The test class that has the main method

```<code>import java.util.Scanner;
public class TestPersonWeight {

    public static void classifyBMI() {
        PersonWeight test1 = new PersonWeight();
        String result="";

        if(test1.ComputeBMI() < 18.5) {
            result = "Underweight ";

        } else if (test1.ComputeBMI() < 25) {
            result = "Normal Weight ";
        }else if (test1.ComputeBMI() < 30) {
            result = "Over Weight ";
        }else  {
            result = "Obese ";
        }
     System.out.printf(result);

    }

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        TestPersonWeight TestPersonWeight = new TestPersonWeight();
        PersonWeight PersonWeight = new PersonWeight()
        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        PersonWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        PersonWeight.setWeight(w);

       PersonWeight.ComputeBMI();
        System.out.printf("%n Height: " + PersonWeight.getHeight());
        System.out.printf("%n Weight: " + PersonWeight.getWeight());
        System.out.printf("%n BMI: " , PersonWeight.ComputeBMI());

    }
}

</code>```

答:
In your program, you're using printf the wrong way. You have some options:

```<code>System.out.printf("%nHeight: %f", PersonWeight.getHeight());
System.out.printf("%nWeight: %f", PersonWeight.getWeight());
System.out.printf("%nBMI: %f", PersonWeight.ComputeBMI());
</code>```

Or just use System.out.println:

```<code>System.out.println("Height: " + PersonWeight.getHeight());
System.out.println("Weight: " + PersonWeight.getWeight());
System.out.println("BMI: " + PersonWeight.ComputeBMI());
</code>```

Basically, your problem is you're using a comma in the last statement, so it's not being printed, but I'm showing you other options too.

Body:
Java 11.6
I am new to Java and trying to create a BMI calculator that will take in Person's weight, height and calculate the BMI. The program takes in the data but does not show any answer for the BMI calculation. Since there are no errors, I am not sure if my algorithm is wrong or basic coding error.

The PersonWeight.java class

import java.time.Year;

public class PersonWeight {

    private double height;
    private double weight;

    public PersonWeight() {

        height = 0;
        weight = 0;

    }

    public PersonWeight(double h, double w) {

        height = h;
        weight = w;

    }

    public void setHeight(double h) {
        this.height = h;
    }

    public double getHeight() {
        return height;
    }

    public void setWeight(double w) {
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    public double ComputeBMI() {

        double bmi = ((weight)/(height*height));
        return bmi;
    }

}

The test class that has the main method

import java.util.Scanner;
public class TestPersonWeight {

    public static void classifyBMI() {
        PersonWeight test1 = new PersonWeight();
        String result="";

        if(test1.ComputeBMI() < 18.5) {
            result = "Underweight ";

        } else if (test1.ComputeBMI() < 25) {
            result = "Normal Weight ";
        }else if (test1.ComputeBMI() < 30) {
            result = "Over Weight ";
        }else  {
            result = "Obese ";
        }
     System.out.printf(result);

    }

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        TestPersonWeight TestPersonWeight = new TestPersonWeight();
        PersonWeight PersonWeight = new PersonWeight()
        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        PersonWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        PersonWeight.setWeight(w);

       PersonWeight.ComputeBMI();
        System.out.printf("%n Height: " + PersonWeight.getHeight());
        System.out.printf("%n Weight: " + PersonWeight.getWeight());
        System.out.printf("%n BMI: " , PersonWeight.ComputeBMI());

    }
}

Body:
In your program, you're using printf the wrong way. You have some options:

System.out.printf("%nHeight: %f", PersonWeight.getHeight());
System.out.printf("%nWeight: %f", PersonWeight.getWeight());
System.out.printf("%nBMI: %f", PersonWeight.ComputeBMI());

Or just use System.out.println:

System.out.println("Height: " + PersonWeight.getHeight());
System.out.println("Weight: " + PersonWeight.getWeight());
System.out.println("BMI: " + PersonWeight.ComputeBMI());

Basically, your problem is you're using a comma in the last statement, so it's not being printed, but I'm showing you other options too.


答:
Your program has an error in the last System.out.printf() command

```<code>System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
 //Should be plus and not a comma (",")
</code>```

Title: Formula not being calculated in Java Class Method

Body:
Your program has an error in the last System.out.printf() command

System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
 //Should be plus and not a comma (",")


问:
How to pass context for an intent from a method of a class?
Error :  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at com.adriitsolutions.prarthana.AdapterForListView.MyRequestForBloodRequirementListRecyclerView$1.onClick(MyRequestForBloodRequirementListRecyclerView.java:153)
        at android.view.View.performClick(View.java:6935)
Here is my code.

java
((myViewHolderForRecyclerViewOfMenu) viewHolder).iv_my_request_view.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        // showLeadDetails(position);
        context.startActivity(new Intent( context , ViewDonorListActivity.class));
        Log.e("ONCLICK", "View Request");
    }
});

```<code>

Adapter :  @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.sendAt.setText(mData.get(position).getSendAt());
        holder.radius.setText(mData.get(position).getRadius());
        holder.acceptedStatus.setText(mData.get(position).getAcceptedStatus());

        holder.requestBloodGrpType.setImageResource(mData.get( position ).getRequestBloodGrpType() );
        //holder.requestUrgenyType.setImageResource( mData.get( position ).getRequestUrgencyType() );

        holder.viewRequest.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        } );

       /* holder.buttonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        });*/

    }
</code>```

答:
you should post your full adapter class, cause we should see where do you initialize mContext.but by default you can get context by constructor method of adapter.

something like:

```<code>private List<Obj> list;
private Context mContext;

public AdapterRvBid(List<Obj> list, Context mContext) {
    this.list = list;
    this.mContext= mContext;
}
</code>```

Body:
Error :  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at com.adriitsolutions.prarthana.AdapterForListView.MyRequestForBloodRequirementListRecyclerView$1.onClick(MyRequestForBloodRequirementListRecyclerView.java:153)
        at android.view.View.performClick(View.java:6935)
Here is my code.

java
((myViewHolderForRecyclerViewOfMenu) viewHolder).iv_my_request_view.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        // showLeadDetails(position);
        context.startActivity(new Intent( context , ViewDonorListActivity.class));
        Log.e("ONCLICK", "View Request");
    }
});

Adapter :  @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.sendAt.setText(mData.get(position).getSendAt());
        holder.radius.setText(mData.get(position).getRadius());
        holder.acceptedStatus.setText(mData.get(position).getAcceptedStatus());

        holder.requestBloodGrpType.setImageResource(mData.get( position ).getRequestBloodGrpType() );
        //holder.requestUrgenyType.setImageResource( mData.get( position ).getRequestUrgencyType() );

        holder.viewRequest.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        } );

       /* holder.buttonView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext,ViewDonorListActivity.class));
            }
        });*/

    }

Body:
you should post your full adapter class, cause we should see where do you initialize mContext.but by default you can get context by constructor method of adapter.

something like:

private List<Obj> list;
private Context mContext;

public AdapterRvBid(List<Obj> list, Context mContext) {
    this.list = list;
    this.mContext= mContext;
}


问:
Trouble with email validation
This time I have another issue when trying to deal with email validation. When I test my app, I fill the Email TextInput with a valid string, something like Hello@email.com, however, the nonValidInput bool stays at null, and subsequent attempts to post the Email adress don't work either, the nonValidInput bool now it's true when it must be false when entering a correct email adress.

The _onSubmit script is called when the button is pressed.

Here's my code:

```<code>state = { username: null, password: null, nonValidInput: null }

_validar = () => {
 let email = this.state.username
 let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

 if(pattern.test(String(email).toLowerCase) == true) {
   this.setState({ nonValidInput: false })
 } else {
   this.setState({ nonValidInput: true })
 }

  console.warn(this.state.nonValidInput)
}

_onSubmit = () =>{
 this._validar()

 if(this.state.nonValidInput == false) {
   const { username, password } = this.state;
 } else {
   this.setState({ nonValidInput: true })
 }
}
</code>```

Again thank you for your answers.

答:
I found a couple of mistakes in your code.

this.setState is an async process. So call your console.warn() as a callback function.

```<code>if (pattern.test(String(this.state.username).toLowerCase()) == true) {
  this.setState({ nonValidInput: false }, () => console.warn("true"));
} else {
  this.setState({ nonValidInput: true }, () => console.warn("false"));
}
</code>```

and make _onSubmit function as async until it process _validar function.

```<code>_onSubmit = async () => {
  await this._validar();
  if (this.state.nonValidInput == false) {
    const { username, password } = this.state;
  } else {
    this.setState({ nonValidInput: true });
  }
};
</code>```

toLowerCase is a method, you can't call it as,

```<code>pattern.test(String(email).toLowerCase)
</code>```

Change it to

```<code>pattern.test(String(email).toLowerCase())
</code>```

Finally i see you are duplicating your code. In order to make your code clean add your validation part inside submit.

```<code>_onSubmit = () => {
  let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  if (pattern.test(String(this.state.username).toLowerCase()) == true) {
    this.setState({ nonValidInput: false });
    // you can call submit
  } else {
    this.setState({ nonValidInput: true });
    // you can handle error
  }
};
</code>```

Hope this helps you. Feel free for doubts.

Title: Trouble with email validation

Body:
This time I have another issue when trying to deal with email validation. When I test my app, I fill the Email TextInput with a valid string, something like Hello@email.com, however, the nonValidInput bool stays at null, and subsequent attempts to post the Email adress don't work either, the nonValidInput bool now it's true when it must be false when entering a correct email adress.

The _onSubmit script is called when the button is pressed.

Here's my code:

state = { username: null, password: null, nonValidInput: null }

_validar = () => {
 let email = this.state.username
 let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

 if(pattern.test(String(email).toLowerCase) == true) {
   this.setState({ nonValidInput: false })
 } else {
   this.setState({ nonValidInput: true })
 }

  console.warn(this.state.nonValidInput)
}

_onSubmit = () =>{
 this._validar()

 if(this.state.nonValidInput == false) {
   const { username, password } = this.state;
 } else {
   this.setState({ nonValidInput: true })
 }
}

Again thank you for your answers.

Body:
I found a couple of mistakes in your code.

this.setState is an async process. So call your console.warn() as a callback function.

if (pattern.test(String(this.state.username).toLowerCase()) == true) {
  this.setState({ nonValidInput: false }, () => console.warn("true"));
} else {
  this.setState({ nonValidInput: true }, () => console.warn("false"));
}

and make _onSubmit function as async until it process _validar function.

_onSubmit = async () => {
  await this._validar();
  if (this.state.nonValidInput == false) {
    const { username, password } = this.state;
  } else {
    this.setState({ nonValidInput: true });
  }
};

toLowerCase is a method, you can't call it as,

pattern.test(String(email).toLowerCase)

Change it to

pattern.test(String(email).toLowerCase())

Finally i see you are duplicating your code. In order to make your code clean add your validation part inside submit.

_onSubmit = () => {
  let pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  if (pattern.test(String(this.state.username).toLowerCase()) == true) {
    this.setState({ nonValidInput: false });
    // you can call submit
  } else {
    this.setState({ nonValidInput: true });
    // you can handle error
  }
};

Hope this helps you. Feel free for doubts.


问:
Is there a way to make a function for all the code relating to drawing a bouncing ball in pygame?
The ball bounces around and I can draw it but I want to draw multiple and have them start at random places without having to type every scenario. Is there a way to write a function to do this?</p>

```<code>import pygame
import sys
import random

pygame.init()

screenSize = (800,600)
screen = pygame.display.set_mode(screenSize)
pygame.display.set_caption("Jacob Cardoso Basic Drawing")

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
x = random.randint(50,750)
y = random.randint(50,550)
dx = random.randint(1, 3)
dy = random.randint(-1, 3)

screen.fill(WHITE)
go = True
while go:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False
    x = x + dx
    y = y + dy

    if (y <= 50) or (y >= 550):
        dy = -dy
        COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
    if (x <= 50) or (x >= 750):
        dx = -dx
        COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    screen.fill(WHITE)
    pygame.draw.circle (screen, COLOUR, (x,y), 50, 0)
    pygame.display.update()

pygame.quit()
sys.exit()
</code>```

答:
Create a Class for the balls. The coordinates, moving direction and color become instance attributes. Move the code which handles the movement to an update method. Do the drawing of the ball in a draw method.

class Ball:
    def __init__(self):
        self.x = random.randint(50,750)
        self.y = random.randint(50,550)
        self.dx = random.randint(1, 3)
        self.dy = random.randint(-1, 3)
        self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    def update(self):
        self.x = self.x + self.dx
        self.y = self.y + self.dy
        bounce = False
        if (self.y <= 50) or (self.y >= 550):
            self.dy = -self.dy
            bounce = True
        if (self.x <= 50) or (self.x >= 750):
            self.dx = -self.dx
            bounce = True
        if bounce:
            self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    def draw(self, surf):
        pygame.draw.circle(surf, self.color, (self.x, self.y), 50, 0)
```

<p>Create a number of (<code>max_balls</code>) ball instances in a loop and append them to a list (<code>balls</code>), before the application loop. Update the position of the balls and draw them in for-loops in the application loop:</p>

<pre class="lang-py prettyprint-override"><code># crate the balls
max_balls = 5
balls = []
for _ in range(max_balls):
    balls.append(Ball())

screen.fill(WHITE)
go = True
while go:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False

    # update the ball positions
    for ball in balls:
        ball.update()

    screen.fill(WHITE)
    # draw the balls
    for ball in balls:
        ball.draw(screen)
    pygame.display.update()
</code>```

Body:
The ball bounces around and I can draw it but I want to draw multiple and have them start at random places without having to type every scenario. Is there a way to write a function to do this?

import pygame
import sys
import random

pygame.init()

screenSize = (800,600)
screen = pygame.display.set_mode(screenSize)
pygame.display.set_caption("Jacob Cardoso Basic Drawing")

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
x = random.randint(50,750)
y = random.randint(50,550)
dx = random.randint(1, 3)
dy = random.randint(-1, 3)

screen.fill(WHITE)
go = True
while go:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False
    x = x + dx
    y = y + dy

    if (y <= 50) or (y >= 550):
        dy = -dy
        COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
    if (x <= 50) or (x >= 750):
        dx = -dx
        COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    screen.fill(WHITE)
    pygame.draw.circle (screen, COLOUR, (x,y), 50, 0)
    pygame.display.update()

pygame.quit()
sys.exit()

Body:
Create a Class for the balls. The coordinates, moving direction and color become instance attributes. Move the code which handles the movement to an update method. Do the drawing of the ball in a draw method.

class Ball:
    def __init__(self):
        self.x = random.randint(50,750)
        self.y = random.randint(50,550)
        self.dx = random.randint(1, 3)
        self.dy = random.randint(-1, 3)
        self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    def update(self):
        self.x = self.x + self.dx
        self.y = self.y + self.dy
        bounce = False
        if (self.y <= 50) or (self.y >= 550):
            self.dy = -self.dy
            bounce = True
        if (self.x <= 50) or (self.x >= 750):
            self.dx = -self.dx
            bounce = True
        if bounce:
            self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    def draw(self, surf):
        pygame.draw.circle(surf, self.color, (self.x, self.y), 50, 0)

Create a number of (max_balls) ball instances in a loop and append them to a list (balls), before the application loop. Update the position of the balls and draw them in for-loops in the application loop:

# crate the balls
max_balls = 5
balls = []
for _ in range(max_balls):
    balls.append(Ball())

screen.fill(WHITE)
go = True
while go:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False

    # update the ball positions
    for ball in balls:
        ball.update()

    screen.fill(WHITE)
    # draw the balls
    for ball in balls:
        ball.draw(screen)
    pygame.display.update()


问:
Rewrite issue with configuring Lighttpd with Flask Python framework
I've run and developed my Flask application without incident using its built-in server. It has worked fine and has been really smooth and fun. Unfortunately, Lighttpd is, as always, a pain to deploy to. I'm following the instructions as closely as I can, but unfortunately, my application still isn't working out.

Here is my configuration so far:

```<code>server.modules   += ( "mod_fastcgi" )
server.modules   += ( "mod_rewrite" )

fastcgi.server = ("/bioinfo/main.fcgi" =>
    ((
        "socket" => "/tmp/bioinfo-fcgi.sock",
        "bin-path" => "/var/www/bioinfo/main.fcgi",
        "check-local" => "disable",
        "max-procs" => 1
    ))
)
fastcgi.debug = 1

url.rewrite-once = (
    "^/bioinfo/static/(.*)$" => "/bioinfo/static/$1",
    "^/bioinfo/(.*)$" => "/bioinfo/main.fcgi/$1"
)

# in: /etc/lighttpd/conf-available/10-fastcgi.conf
</code>```

This works in that it displays the main page, but not any subsequent pages.

I have several app.route handlers in my Flask application which I access using either GET or POST using some XHR in the client.

Also, here's my .fcgi file, just to make sure I don't have any glaring errors here:

```<code>#!/usr/bin/python
from flup.server.fcgi import WSGIServer
from main import app

if __name__ == '__main__':
    WSGIServer(app).run()
</code>```

If anyone can identify the problem, being, AJAX doesn't work with the application's URIs (most likely because my rewrite rules are wonky), I'd really appreciate it. Thanks in advance, folks!

答: You need to chdir to the directory your application is running in manually.</p>

Body:
I've run and developed my Flask application without incident using its built-in server. It has worked fine and has been really smooth and fun. Unfortunately, Lighttpd is, as always, a pain to deploy to. I'm following the instructions as closely as I can, but unfortunately, my application still isn't working out.

Here is my configuration so far:

server.modules   += ( "mod_fastcgi" )
server.modules   += ( "mod_rewrite" )

fastcgi.server = ("/bioinfo/main.fcgi" =>
    ((
        "socket" => "/tmp/bioinfo-fcgi.sock",
        "bin-path" => "/var/www/bioinfo/main.fcgi",
        "check-local" => "disable",
        "max-procs" => 1
    ))
)
fastcgi.debug = 1

url.rewrite-once = (
    "^/bioinfo/static/(.*)$" => "/bioinfo/static/$1",
    "^/bioinfo/(.*)$" => "/bioinfo/main.fcgi/$1"
)

# in: /etc/lighttpd/conf-available/10-fastcgi.conf

This works in that it displays the main page, but not any subsequent pages.

I have several app.route handlers in my Flask application which I access using either GET or POST using some XHR in the client.

Also, here's my .fcgi file, just to make sure I don't have any glaring errors here:

#!/usr/bin/python
from flup.server.fcgi import WSGIServer
from main import app

if __name__ == '__main__':
    WSGIServer(app).run()

If anyone can identify the problem, being, AJAX doesn't work with the application's URIs (most likely because my rewrite rules are wonky), I'd really appreciate it. Thanks in advance, folks!


问:
VueJS: $router.push not working with query parameters
In my NuxtJS(v. 2.10.2) application, I have a URL like below where pid is a post's id.

/post?pid=5e4844e34202d6075e593062

This URL works fine and loads the post as per the value passed to the pid query parameter. However, user can add new post by clicking Add Post button on the application bar that opens a dialog. Once the user clicks add, a request to back-end server is made to save the request. And once successful, user is redirected to the new post using vue router push like below

```<code>.then(data => {
  if (data) {
    this.$router.push({ path: `/post?pid=${data.id}` });
  }
})
</code>```

The problem is, user is not redirected to the new post, only the query parameter pid is updated. I suspect VueJS does not acknowledge this as a different URL and hence does nothing.

How to fix this?

Update: As an alternative tried the syntax below but getting the same behavior.

```<code>this.$router.push({ path: "post", query: { pid: data.id } });
</code>```

答:
try this :

```<code>.then(data => {
  if (data) {
    this.$router.push('/post?pid=' + data.id);
  }
})
</code>```

hope it works!!!

Body:
In my NuxtJS(v. 2.10.2) application, I have a URL like below where pid is a post's id.

/post?pid=5e4844e34202d6075e593062

This URL works fine and loads the post as per the value passed to the pid query parameter. However, user can add new post by clicking Add Post button on the application bar that opens a dialog. Once the user clicks add, a request to back-end server is made to save the request. And once successful, user is redirected to the new post using vue router push like below

.then(data => {
  if (data) {
    this.$router.push({ path: `/post?pid=${data.id}` });
  }
})

The problem is, user is not redirected to the new post, only the query parameter pid is updated. I suspect VueJS does not acknowledge this as a different URL and hence does nothing.

How to fix this?

Update: As an alternative tried the syntax below but getting the same behavior.

this.$router.push({ path: "post", query: { pid: data.id } });

Body:
try this :

.then(data => {
  if (data) {
    this.$router.push('/post?pid=' + data.id);
  }
})

hope it works!!!