问:
How to check if array contains other array objects [JS]
I'm trying to make a basic javascript algorithim. Im trying to make a basic 'enjoyability' scale.
Basically if the array "tags", contains an object from "interests" add 1 to enjoyability. If the array "tags" contains an object from "dislikes" subtract 1 from enjoyability.
How can I do this?

const fs = require('fs');
var interests = ["gaming", "coding", "dogs", "food"];
var dislikes = ["cats", "school", "work", "politics"];
var tags = ["gaming", "dogs", "school", "food", "coding"];
var enjoyability = 0;
var enjoyable = 0;
var PosOrNeg = 0;
var isIn;
const intr = tags.some(r=> interests.indexOf(r) >= 4)
const disl = tags.some(r=> dislikes.indexOf(r) >= 0)

if (intr == true) {
    console.log('a')
}

function run() {

console.log('a'+enjoyability)
    console.log(tags.includes())
    if (enjoyability >= 0) {
        enjoyable = 0;
        console.log("yes")
    } else {
        enjoyable < 0;
        console.log("no")
    }
}
console.log(intr)
console.log(disl)
console.log(enjoyable)
run()
```

答:
for loop

const interests = ['gaming', 'coding', 'dogs', 'food'];
const dislikes = ['cats', 'school', 'work', 'politics'];

const tags = ['gaming', 'dogs', 'school', 'food', 'coding'];

let enjoyability = 0;

for (const tag of tags) {
    if (interests.find((item) => item === tag)) enjoyability++;
    if (dislikes.find((item) => item === tag)) enjoyability--;
}

console.log(enjoyability);```


来源: stackexchange

问:
Cannot stop useEffect() from executing
My application, pulls data ( text, numbers) from a database and then places them in a canvas image. This is working as expected, and the data is being displayed along with a few lines of the final diagram. However the useEffect() function is not stopping and continues to display the same image, which I would not have realised had I not placed an alert.

I have seen the documentation and other questions that have discussed this problem. I understand that I need to put a variable whose value will not change. But I am simply unable to do this. I am sharing my code. Will be grateful if someone can help.

```<code>import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router";
import './cindex.css';

export default function GetChartData() {
 const params = useParams();
 const [dbdata, setData] = useState('empty52');
 const canvas = useRef();
 let ctx = null;
 let name = null
 let Lalong = null
 let T1 = { text: 'dummy', x: 180, y: 100 }
 let T2 = { text: 'dummy', x: 180, y: 200 }

 useEffect(() => {
   async function getData() {
   const response = await fetch(`http://localhost:5000/getchartdata/${params.id.toString()}`);
   //const response = await fetch(`http://khona21.cleverapps.io/getchartdata/${params.id.toString()}`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     setData(dbdata);
   }
   getData();
   return;
   },[dbdata]);

 // initialize the canvas context

  useEffect(() => {

    // dynamically assign the width and height to canvas
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;
    // get context of the canvas
    ctx = canvasEle.getContext("2d");
  //}, []);
  }, [T1,T2]);

 useEffect(() => {

   let pid = dbdata.pid;
   let spid = JSON.stringify(pid);
   if (typeof spid !== 'undefined'){
       name = dbdata.pid.name;
       Lalong = dbdata.GLon.La
       if (T1.text === 'dummy') {
           T1.text = name
           T2.text = Lalong.toString()
       }
       }
    else {
       //window.alert('undefined')
   }

    drawLine({ x: 150, y: 20, x1: 150, y1: 450 });
    drawLine({ x: 300, y: 20, x1: 300, y1: 450 });

    writeText(T1);
    writeText(T2);
    window.alert('finished drawing')

  //}, []);
  //}, [[]]);
  }, [T1]);

  const drawLine = (info, style = {}) => {
    const { x, y, x1, y1 } = info;
    const { color = 'black', width = 1 } = style;

    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x1, y1);
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.stroke();
  }

  // write a text
  const writeText = (info, style = {}) => {
  const { text, x, y } = info;
  const { fontSize = 20, fontFamily = 'Arial', color = 'black', textAlign = 'left', textBaseline = 'top' } = style;

  ctx.beginPath();
  ctx.font = fontSize + 'px ' + fontFamily;
  ctx.textAlign = textAlign;
  ctx.textBaseline = textBaseline;
  ctx.fillStyle = color;
  ctx.fillText(text, x, y);
  ctx.stroke();
}

 return (
   <div>
     <h3>Chart Positions</h3>
     <p>{JSON.stringify(dbdata)}</p>
     <hr></hr>
     <canvas ref={canvas}></canvas>
   </div>
 );

}
</code>```

I have tried to ensure that that the text in T1 changes only once and hence should stop the loop. But it is not. What should I do?

答:
the TRICK was to use [dbdata.length] instead of simply [dbdata] as the stopping condition in the useEffect() function. dbdata was being set each time as new, but dbdata.length was not changing.

```<code>import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router";
import './cindex.css';

 //let T1 = { text: 'dummy', x: 180, y: 100 }
 //let T2 = { text: 'dummy', x: 180, y: 200 }

export default function GetChartData() {

 const canvas = useRef();
 let ctx = null;

 const params = useParams();
 const [dbdata, setData] = useState('empty52');

 let name = null
 let Lalong = null
 const T1 = { text: 'dummy', x: 180, y: 100 }
 const T2 = { text: 'dummy', x: 180, y: 200 }

 useEffect(() => {

   async function getData() {
   const response = await fetch(`http://localhost:5000/getchartdata/${params.id.toString()}`);
   //const response = await fetch(`http://khona21.cleverapps.io/getchartdata/${params.id.toString()}`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     setData(dbdata);

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

   let pid = dbdata.pid;
   let spid = JSON.stringify(pid);
   if (typeof spid !== 'undefined'){
       name = dbdata.pid.name;
       Lalong = dbdata.GLon.La
       T1.text = name
       T2.text = Lalong.toString()
       }
    else {
       //window.alert('undefined')
   }

    // dynamically assign the width and height to canvas
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;
    // get context of the canvas
    ctx = canvasEle.getContext("2d");

    drawLine({ x: 150, y: 20, x1: 150, y1: 450 });
    drawLine({ x: 300, y: 20, x1: 300, y1: 450 });

    writeText(T1);
    writeText(T2);
    window.alert('image drawn')

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

   }

   getData();

   return;
   },[dbdata.length]);

  const drawLine = (info, style = {}) => {
    const { x, y, x1, y1 } = info;
    const { color = 'black', width = 1 } = style;

    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x1, y1);
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.stroke();
  }

  // write a text
  const writeText = (info, style = {}) => {
  const { text, x, y } = info;
  const { fontSize = 20, fontFamily = 'Arial', color = 'black', textAlign = 'left', textBaseline = 'top' } = style;

  ctx.beginPath();
  ctx.font = fontSize + 'px ' + fontFamily;
  ctx.textAlign = textAlign;
  ctx.textBaseline = textBaseline;
  ctx.fillStyle = color;
  ctx.fillText(text, x, y);
  ctx.stroke();
}

 return (
   <div>
     <h3>Chart Positions</h3>
     <p>{JSON.stringify(dbdata)}</p>
     <hr></hr>
     <canvas ref={canvas}></canvas>
   </div>
 );

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cannot stop useEffect() from executing

Body:
My application, pulls data ( text, numbers) from a database and then places them in a canvas image. This is working as expected, and the data is being displayed along with a few lines of the final diagram. However the useEffect() function is not stopping and continues to display the same image, which I would not have realised had I not placed an alert.

I have seen the documentation and other questions that have discussed this problem. I understand that I need to put a variable whose value will not change. But I am simply unable to do this. I am sharing my code. Will be grateful if someone can help.

import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router";
import './cindex.css';

export default function GetChartData() {
 const params = useParams();
 const [dbdata, setData] = useState('empty52');
 const canvas = useRef();
 let ctx = null;
 let name = null
 let Lalong = null
 let T1 = { text: 'dummy', x: 180, y: 100 }
 let T2 = { text: 'dummy', x: 180, y: 200 }

 useEffect(() => {
   async function getData() {
   const response = await fetch(`http://localhost:5000/getchartdata/${params.id.toString()}`);
   //const response = await fetch(`http://khona21.cleverapps.io/getchartdata/${params.id.toString()}`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     setData(dbdata);
   }
   getData();
   return;
   },[dbdata]);

 // initialize the canvas context

  useEffect(() => {

    // dynamically assign the width and height to canvas
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;
    // get context of the canvas
    ctx = canvasEle.getContext("2d");
  //}, []);
  }, [T1,T2]);

 useEffect(() => {

   let pid = dbdata.pid;
   let spid = JSON.stringify(pid);
   if (typeof spid !== 'undefined'){
       name = dbdata.pid.name;
       Lalong = dbdata.GLon.La
       if (T1.text === 'dummy') {
           T1.text = name
           T2.text = Lalong.toString()
       }
       }
    else {
       //window.alert('undefined')
   }

    drawLine({ x: 150, y: 20, x1: 150, y1: 450 });
    drawLine({ x: 300, y: 20, x1: 300, y1: 450 });

    writeText(T1);
    writeText(T2);
    window.alert('finished drawing')

  //}, []);
  //}, [[]]);
  }, [T1]);

  const drawLine = (info, style = {}) => {
    const { x, y, x1, y1 } = info;
    const { color = 'black', width = 1 } = style;

    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x1, y1);
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.stroke();
  }

  // write a text
  const writeText = (info, style = {}) => {
  const { text, x, y } = info;
  const { fontSize = 20, fontFamily = 'Arial', color = 'black', textAlign = 'left', textBaseline = 'top' } = style;

  ctx.beginPath();
  ctx.font = fontSize + 'px ' + fontFamily;
  ctx.textAlign = textAlign;
  ctx.textBaseline = textBaseline;
  ctx.fillStyle = color;
  ctx.fillText(text, x, y);
  ctx.stroke();
}

 return (

Chart Positions

{JSON.stringify(dbdata)}

     <canvas ref={canvas}></canvas>

 );

}

I have tried to ensure that that the text in T1 changes only once and hence should stop the loop. But it is not. What should I do?

Body:
the TRICK was to use [dbdata.length] instead of simply [dbdata] as the stopping condition in the useEffect() function. dbdata was being set each time as new, but dbdata.length was not changing.

import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router";
import './cindex.css';

 //let T1 = { text: 'dummy', x: 180, y: 100 }
 //let T2 = { text: 'dummy', x: 180, y: 200 }

export default function GetChartData() {

 const canvas = useRef();
 let ctx = null;

 const params = useParams();
 const [dbdata, setData] = useState('empty52');

 let name = null
 let Lalong = null
 const T1 = { text: 'dummy', x: 180, y: 100 }
 const T2 = { text: 'dummy', x: 180, y: 200 }

 useEffect(() => {

   async function getData() {
   const response = await fetch(`http://localhost:5000/getchartdata/${params.id.toString()}`);
   //const response = await fetch(`http://khona21.cleverapps.io/getchartdata/${params.id.toString()}`);

     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }

     const dbdata = await response.json();
     setData(dbdata);

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

   let pid = dbdata.pid;
   let spid = JSON.stringify(pid);
   if (typeof spid !== 'undefined'){
       name = dbdata.pid.name;
       Lalong = dbdata.GLon.La
       T1.text = name
       T2.text = Lalong.toString()
       }
    else {
       //window.alert('undefined')
   }

    // dynamically assign the width and height to canvas
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;
    // get context of the canvas
    ctx = canvasEle.getContext("2d");

    drawLine({ x: 150, y: 20, x1: 150, y1: 450 });
    drawLine({ x: 300, y: 20, x1: 300, y1: 450 });

    writeText(T1);
    writeText(T2);
    window.alert('image drawn')

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

   }

   getData();

   return;
   },[dbdata.length]);

  const drawLine = (info, style = {}) => {
    const { x, y, x1, y1 } = info;
    const { color = 'black', width = 1 } = style;

    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x1, y1);
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.stroke();
  }

  // write a text
  const writeText = (info, style = {}) => {
  const { text, x, y } = info;
  const { fontSize = 20, fontFamily = 'Arial', color = 'black', textAlign = 'left', textBaseline = 'top' } = style;

  ctx.beginPath();
  ctx.font = fontSize + 'px ' + fontFamily;
  ctx.textAlign = textAlign;
  ctx.textBaseline = textBaseline;
  ctx.fillStyle = color;
  ctx.fillText(text, x, y);
  ctx.stroke();
}

 return (
   <div>
     <h3>Chart Positions</h3>
     <p>{JSON.stringify(dbdata)}</p>
     <hr></hr>
     <canvas ref={canvas}></canvas>
   </div>
 );

}


问:
Get xargs to allow multiple arguments to command
I've got a file of arguments:

file.txt:

1 2 3
a b c
4 5 6
```
<p>I want to pass them to a command that takes 3 arguments. As a minimal example, <code>xargs</code> will parse a command as a single string if you use "-I" directly:</p>
<pre class="lang-sh prettyprint-override"><code>echo '1 2 3' | xargs -I@ python -c "import sys; print(sys.argv)" @
>>> ['-c', '1 2 3']
</code>```

Strangely, the $(echo ...) trick doesn't work:

echo '1 2 3' | xargs -I@ python -c "import sys; print(sys.argv)" $(echo @)
>>> ['-c', '1 2 3']
```
<p>Even though a string literal in the same place would:</p>
<pre class="lang-sh prettyprint-override"><code>echo '1 2 3' | xargs -I@ python -c "import sys; print(sys.argv)" $(echo '1 2 3')
>>> ['-c', '1', '2', '3']
</code>```

答:
```<code>xargs -n 3 cmd
</code>```

Executes cmd, with a maximum of three arguments at a time.

For example:

```<code>xargs -n 3 echo < file.txt
# gives
1 2 3
a b c
4 5 6

xargs -n 2 echo < file.txt
# gives
1 2
3 a
b c
4 5
6
</code>```

Body:
I've got a file of arguments:

file.txt:

1 2 3
a b c
4 5 6

I want to pass them to a command that takes 3 arguments. As a minimal example, xargs will parse a command as a single string if you use "-I" directly:

echo '1 2 3' | xargs -I@ python -c "import sys; print(sys.argv)" @
>>> ['-c', '1 2 3']

Strangely, the $(echo ...) trick doesn't work:

echo '1 2 3' | xargs -I@ python -c "import sys; print(sys.argv)" $(echo @)
>>> ['-c', '1 2 3']

Even though a string literal in the same place would:

echo '1 2 3' | xargs -I@ python -c "import sys; print(sys.argv)" $(echo '1 2 3')
>>> ['-c', '1', '2', '3']

Body:
xargs -n 3 cmd

Executes cmd, with a maximum of three arguments at a time.

For example:

xargs -n 3 echo < file.txt
# gives
1 2 3
a b c
4 5 6

xargs -n 2 echo < file.txt
# gives
1 2
3 a
b c
4 5
6


问:
Custom Authentication in PowerBI
I'm looking a solution to combine Power BI authentication and a web application.
We authenticate our users using existing web application and let them see the dashboard and reports in Power BI portal, the existing users are external customers who don't have internal AD accounts.

Following solution will redirect user to a login page always.
https://github.com/Microsoft/Reporting-Services/tree/master/CustomSecuritySample

But what I need is that once the user has been authenticated using our web application, Power BI let the users see the dashboards without any more authentication.

答:
I forked Microsoft's Custom Security Sample to do just what you are describing (needed the functionality at a client long ago and reimplemented as a shareable project on GitHub).

https://github.com/sonrai-LLC/ExtRSAuth

I created a YouTube walkthrough as well to show how one can extend and debug SSRS security with this ExtRSAuth SSRS security assembly https://www.youtube.com/watch?v=tnsWChwW7lA

TL; DR; just bypass the Microsoft example auth check in Login.aspx.cs and put your auth in Page_Load() or Page_Init() event of Login.aspx.cs- wherever you want to perform some custom logging check- and then immediately redirect auth'd user to their requested URI.

Title: Custom Authentication in PowerBI


问:
Have one object call the functions for two objects?

class foo{
 public:

  void print();
  void alert();
  bool get_state();
};

class bar: public foo{};

bar master;
bar slave;
```
<p>Is there a way to have calls to <code>slave</code> call the same function for <code>slave</code> and <code>master</code>?</p>
<p>There are unfortunately 2 catches.</p>
<ol>
<li>This should not be implemented for all functions.</li>
</ol>
<pre class="lang-cpp prettyprint-override"><code>master.get_state() //Returns master.get_state()
slave.get_state()  //Returns master.get_state() || slave.get_state()

master.alert() //Calls master.alert()
slave.alert()  //Calls master.alert() and slave.alert()

master.print() //Calls master.print()
slave.print()  //Calls slave.print()
</code>```

I also don't have access to the implementation of foo and I would definitely prefer not having to override all of foo's functions in bar.

答:
Is there a way to have calls to slave call the same function for slave and master?

No, an object is an object, not two objects. In no language is it possible to combine two different objects into one, because they hold different states and combining them breaks the basic concept of "object". If you find it a necessity, it implies either you are not clear about what you want, or there may be design flaws in foo.

I'm not sure about what you are trying to achieve, here are some hints.

If you are trying to call the non-virtual methods of the base class, use this->BASE::METHOD to break the shadow:

#include <iostream>

class foo {
public:
    void print() { // Impls just for demonstration
        std::cout << "printed by foo" << std::endl;
    };
    void alert() {
        std::cout << "alert from foo" << std::endl;
    };
    bool get_state() {
        return false;
    };
};

class bar : public foo {
public:
    void print() {
        this->foo::print();
        std::cout << "printed by bar" << std::endl;
    }
    void alert() {
        this->foo::alert();
        std::cout << "alert from bar" << std::endl;
    }
    bool get_state() {
        bool my_state = true;
        return my_state || this->foo::get_state();
    }
};

int main() {
    foo master;
    bar slave;

    std::cout << "MASTER: " << std::boolalpha << master.get_state() << std::endl;
    master.print();
    master.alert();

    std::cout << "\nSLAVE: " << std::boolalpha << slave.get_state() << std::endl;
    slave.print();
    slave.alert();
}
```
<p>Output:</p>
```MASTER: false
printed by foo
alert from foo

SLAVE: true
printed by foo
printed by bar
alert from foo
alert from bar
```
<hr />
<p>Or, if you want two <code>foo</code>s, but you don't want two objects on the caller's side, favor composition over inheritance.</p>
<pre class="lang-cpp prettyprint-override"><code>class composition {
private:
    foo _master;
    foo _slave;

public:
    void combinedPrint() {
        _master.print();
        _slave.print();
    }
    // same for alert() and get_state()
};
</code>```

Or, if you want the above composition, but you REALLY need composition to behave like a foo (i.e. you're hiding the caller from the fact that composition is actually a holder of two foos), extract an interface:

class IFoo {
public:
    virtual ~IFoo() = default;

    virtual void print() = 0;
    virtual void alert() = 0;
    virtual bool get_state() = 0;
};
```
<p>And modify <code>foo</code> to implement <code>IFoo</code> (yes you'd have to, but in a simple, non-destructive way):</p>
<pre class="lang-cpp prettyprint-override"><code>class foo : IFoo { /* Body unmodified... */ }
</code>```

Also composition:

class composition : IFoo {
private:
    foo _master;
    foo _slave;

public:
    void print() {
        _master.print();
        _slave.print();
    };
    // same for alert() and get_state()
};
```

Body:
class foo{
 public:

  void print();
  void alert();
  bool get_state();
};

class bar: public foo{};

bar master;
bar slave;

Is there a way to have calls to slave call the same function for slave and master?

There are unfortunately 2 catches.

This should not be implemented for all functions.

master.get_state() //Returns master.get_state()
slave.get_state()  //Returns master.get_state() || slave.get_state()

master.alert() //Calls master.alert()
slave.alert()  //Calls master.alert() and slave.alert()

master.print() //Calls master.print()
slave.print()  //Calls slave.print()

I also don't have access to the implementation of foo and I would definitely prefer not having to override all of foo's functions in bar.

Body:
Is there a way to have calls to slave call the same function for slave and master?

No, an object is an object, not two objects. In no language is it possible to combine two different objects into one, because they hold different states and combining them breaks the basic concept of "object". If you find it a necessity, it implies either you are not clear about what you want, or there may be design flaws in foo.

I'm not sure about what you are trying to achieve, here are some hints.

If you are trying to call the non-virtual methods of the base class, use this->BASE::METHOD to break the shadow:

#include <iostream>

class foo {
public:
    void print() { // Impls just for demonstration
        std::cout << "printed by foo" << std::endl;
    };
    void alert() {
        std::cout << "alert from foo" << std::endl;
    };
    bool get_state() {
        return false;
    };
};

class bar : public foo {
public:
    void print() {
        this->foo::print();
        std::cout << "printed by bar" << std::endl;
    }
    void alert() {
        this->foo::alert();
        std::cout << "alert from bar" << std::endl;
    }
    bool get_state() {
        bool my_state = true;
        return my_state || this->foo::get_state();
    }
};

int main() {
    foo master;
    bar slave;

    std::cout << "MASTER: " << std::boolalpha << master.get_state() << std::endl;
    master.print();
    master.alert();

    std::cout << "\nSLAVE: " << std::boolalpha << slave.get_state() << std::endl;
    slave.print();
    slave.alert();
}

Output:

MASTER: false
printed by foo
alert from foo

SLAVE: true
printed by foo
printed by bar
alert from foo
alert from bar

Or, if you want two foos, but you don't want two objects on the caller's side, favor composition over inheritance.

class composition {
private:
    foo _master;
    foo _slave;

public:
    void combinedPrint() {
        _master.print();
        _slave.print();
    }
    // same for alert() and get_state()
};

Or, if you want the above composition, but you REALLY need composition to behave like a foo (i.e. you're hiding the caller from the fact that composition is actually a holder of two foos), extract an interface:

class IFoo {
public:
    virtual ~IFoo() = default;

    virtual void print() = 0;
    virtual void alert() = 0;
    virtual bool get_state() = 0;
};

And modify foo to implement IFoo (yes you'd have to, but in a simple, non-destructive way):

class foo : IFoo { /* Body unmodified... */ }

Also composition:

class composition : IFoo {
private:
    foo _master;
    foo _slave;

public:
    void print() {
        _master.print();
        _slave.print();
    };
    // same for alert() and get_state()
};


问:
[openGauss]Please use "ALTER ROLE "user" PASSWORD 'password';" to set the password of the user before other operations
The system prompts me to change the password each time the openGauss database is installed.
To initialize the openGauss database, my steps as follows:

step1:
gs_initdb -D /data2/openGauss/install --nodename='datanode'

step2：
gaussdb -D /data2/openGauss/install --single_node -p 12300 &

step3:
gsql -d postgres -p 12300 -r

After the connection is successful, the system prompts me to change the password when run the SQL statement:

Please use "ALTER ROLE "user" PASSWORD 'password';" to set the password of the user before other operations!

My question is how to avoid changing the password after each installation.

答:
You can specifies the password of the database administrator by running commands during the running of gs_initdb, and the first step can be changed to

step1': gs_initdb -D /data2/openGauss/install --nodename='datanode' -w 'YourPassword~'


问:
Lombok/Eclipse Issues - I can compile but I cannot run
I'm having an issue with Lombok or Eclipse, not sure which. I have a Spring Boot maven project for which I am using Lombok. I've added this in my pom.xml file and I've used the lombok install for eclipse.

Whats happening is that I can do a mvn clean and a mvn install and a maven update on the project and everything builds as expected. As soon as I go to run the project errors start to appear and I get error such as:

```<code>java.lang.Error: Unresolved compilation problems:
    The method getxxx() is undefined for the type xxxxxx
</code>```

Is there anything that can happen when running the project that can some how strip out lombok?!

I'm running Eclipse Oxygen (4.7.3) with lombok v1.16.18 "Dancing Elephant" any help would be much appreciated.

答:
Adding the tag <annotationProcessorPaths> to pom.xml solved my same problem.

```<code><build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>RELEASE</version>
                    </path>
                </annotationProcessorPaths>
                ...
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

Body:
I'm having an issue with Lombok or Eclipse, not sure which. I have a Spring Boot maven project for which I am using Lombok. I've added this in my pom.xml file and I've used the lombok install for eclipse.

Whats happening is that I can do a mvn clean and a mvn install and a maven update on the project and everything builds as expected. As soon as I go to run the project errors start to appear and I get error such as:

java.lang.Error: Unresolved compilation problems:
    The method getxxx() is undefined for the type xxxxxx

Is there anything that can happen when running the project that can some how strip out lombok?!

I'm running Eclipse Oxygen (4.7.3) with lombok v1.16.18 "Dancing Elephant" any help would be much appreciated.

Body:
Adding the tag <annotationProcessorPaths> to pom.xml solved my same problem.

<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>RELEASE</version>
                    </path>
                </annotationProcessorPaths>
                ...
            </configuration>
        </plugin>
    </plugins>
</build>


问:
Save multiple records of same model in ASP.NET 5
I have a form where user need to enter first name, last name, email, cell phone and address. If the user is a group, then everything except address needs to be added again. My current code can save only one personal and address detail. Could you please guide me on how to change the code to accommodate this need?

I created three viewmodels

PersonViewModel

```<code>  public class PersonViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string CellNumber { get; set; }
    }
</code>```

AddressViewModel

```<code>   public class AddressViewModel
    {
        public string StreetName { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
    }
</code>```

FamilyViewModel

```<code>   public class FamilyViewModel
    {
        public PersonViewModel Person { get; set; }
        public AddressViewModel Address { get; set; }
    }
</code>```

cshtml file

```<code>@model WebApplication2.ViewModels.FamilyViewModel
@{
    Layout = "_Layout";
}

<form asp-controller="Register" asp-action="SaveDetails" method="post">
    <br /><br />
    <div class="row">
        <div class="col">
            <label asp-for="Person.FirstName"></label>
            <input asp-for="Person.FirstName" />
        </div>
        <div class="col">
            <label asp-for="Person.LastName"></label>
            <input asp-for="Person.LastName" />
        </div>
    </div>
    <div class="row" id="">
        <div class="col">
            <label asp-for="Person.Email"></label>
            <input asp-for="Person.Email" />
        </div>
        <div class="col">
            <label asp-for="Person.CellNumber"></label>
            <input asp-for="Person.CellNumber" />
        </div>
    </div>
    <div class="row">
        <div class="col">
            <label asp-for="Address.StreetName"></label>
            <input asp-for="Address.StreetName" />
        </div>
        <div class="col">
            <label asp-for="Address.City"></label>
            <input asp-for="Address.City" />
        </div>
    </div>
     <div class="row">
        <div class="col">
            <label asp-for="Address.PostalCode"></label>
            <input asp-for="Address.PostalCode" />
        </div>
    </div>
    <div><br /><br /></div>
    <div class="row">
        <div class="col-sm-3">
            <a class="btn btn-primary" id="addMore">Add More Member of Group</a>
        </div>
        <div class="col-sm-3">
            <button class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>
</code>```

Controller Action

```<code>[HttpPost]
        public IActionResult SaveDetails(FamilyViewModel familyViewModel)
        {
            //Console.WriteLine("Reached action");
            if (ModelState.IsValid)
            {
                PersonalDetail personalDetail = new PersonalDetail
                {
                    FirstName = familyViewModel.Person.FirstName,
                    LastName = familyViewModel.Person.LastName,
                    Email = familyViewModel.Person.Email,
                    CellNumber = familyViewModel.Person.CellNumber
                };
                Address address = new Address
                {
                    StreetName = familyViewModel.Address.StreetName,
                    City = familyViewModel.Address.City,
                    PostalCode = familyViewModel.Address.PostalCode
                };
                context.PersonalDetails.Add(personalDetail);
                context.Address.Add(address);
                context.SaveChanges();
            }
            return View(familyViewModel);
        }
</code>```

Thank you
Jeremy

答:
I suggest you need add AddressID in your PersonViewModel Class. When you want create a group data, you can pass the params to your page.

My test code.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Net5_MVC.Models
{
    public class PersonViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string CellNumber { get; set; }
        public string AddressID { get; set; }
    }
    public class AddressViewModel
    {
        public string ID { get; set; }
        public string StreetName { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
    }
    public class FamilyViewModel
    {
        public List<PersonViewModel> Person { get; set; }
        public List<AddressViewModel> Address { get; set; }
    }
}
</code>```

My test cshtml

```<code>@model Net5_MVC.Models.FamilyViewModel
@{
    ViewData["Title"] = "https://stackoverflow.com/questions/71086541/save-multiple-records-of-same-model-in-asp-net-5";
    int personcount = 3;
    int addresscount = 1;
    string AddressID = Guid.NewGuid().ToString();
}

<form asp-controller="Home" asp-action="SaveDetails" method="post">
    <br /><br />
    <h3>Person Area</h3>
    @for (int i = 0; i < personcount; i++)
    {
        <input asp-for="Person[i].AddressID" value="@AddressID" hidden="hidden" />
        <div class="row">
            <div class="col">
                <label asp-for=" Person[i].FirstName"></label>
                <input asp-for="Person[i].FirstName" />
            </div>
            <div class="col">
                <label asp-for="Person[i].LastName"></label>
                <input asp-for="Person[i].LastName" />
            </div>
        </div>
        <div class="row" id="">
            <div class="col">
                <label asp-for="Person[i].Email"></label>
                <input asp-for="Person[i].Email" />
            </div>
            <div class="col">
                <label asp-for="Person[i].CellNumber"></label>
                <input asp-for="Person[i].CellNumber" />
            </div>
        </div>
        <hr />
    }

    <h3>Address Area</h3>
    @for (int i = 0; i < addresscount; i++)
    {
        <input asp-for="Address[i].ID" value="@AddressID"  hidden="hidden" />
        <div class="row">
            <div class="col">
                <label asp-for="Address[i].StreetName"></label>
                <input asp-for="Address[i].StreetName" />
            </div>
            <div class="col">
                <label asp-for="Address[i].City"></label>
                <input asp-for="Address[i].City" />
            </div>
        </div>
        <div class="row">
            <div class="col">
                <label asp-for="Address[i].PostalCode"></label>
                <input asp-for="Address[i].PostalCode" />
            </div>
        </div>
        <hr />
    }

    <div><br /><br /></div>
    <div class="row">
        <div class="col-sm-3">
            <a class="btn btn-primary" id="addMore">Add More Member of Group</a>
        </div>
        <div class="col-sm-3">
            <button class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>
</code>```

Test Method

```<code>[HttpPost]
public IActionResult SaveDetails(FamilyViewModel familyViewModel)
{
    List<PersonViewModel> personlist = familyViewModel.Person;
    List<AddressViewModel> addresslist = familyViewModel.Address;
    return Ok();
}
</code>```

Test Result

Body:
I have a form where user need to enter first name, last name, email, cell phone and address. If the user is a group, then everything except address needs to be added again. My current code can save only one personal and address detail. Could you please guide me on how to change the code to accommodate this need?

I created three viewmodels

PersonViewModel

  public class PersonViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string CellNumber { get; set; }
    }

AddressViewModel

   public class AddressViewModel
    {
        public string StreetName { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
    }

FamilyViewModel

   public class FamilyViewModel
    {
        public PersonViewModel Person { get; set; }
        public AddressViewModel Address { get; set; }
    }

cshtml file

@model WebApplication2.ViewModels.FamilyViewModel
@{
    Layout = "_Layout";
}

<form asp-controller="Register" asp-action="SaveDetails" method="post">

            <input asp-for="Person.FirstName" />

            <input asp-for="Person.LastName" />

            <input asp-for="Person.Email" />

            <input asp-for="Person.CellNumber" />

            <input asp-for="Address.StreetName" />

            <input asp-for="Address.City" />

            <input asp-for="Address.PostalCode" />

            Add More Member of Group

            <button class="btn btn-primary">Submit</button>

</form>

Controller Action

[HttpPost]
        public IActionResult SaveDetails(FamilyViewModel familyViewModel)
        {
            //Console.WriteLine("Reached action");
            if (ModelState.IsValid)
            {
                PersonalDetail personalDetail = new PersonalDetail
                {
                    FirstName = familyViewModel.Person.FirstName,
                    LastName = familyViewModel.Person.LastName,
                    Email = familyViewModel.Person.Email,
                    CellNumber = familyViewModel.Person.CellNumber
                };
                Address address = new Address
                {
                    StreetName = familyViewModel.Address.StreetName,
                    City = familyViewModel.Address.City,
                    PostalCode = familyViewModel.Address.PostalCode
                };
                context.PersonalDetails.Add(personalDetail);
                context.Address.Add(address);
                context.SaveChanges();
            }
            return View(familyViewModel);
        }

Thank you
Jeremy

Body:
I suggest you need add AddressID in your PersonViewModel Class. When you want create a group data, you can pass the params to your page.

My test code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Net5_MVC.Models
{
    public class PersonViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string CellNumber { get; set; }
        public string AddressID { get; set; }
    }
    public class AddressViewModel
    {
        public string ID { get; set; }
        public string StreetName { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
    }
    public class FamilyViewModel
    {
        public List<PersonViewModel> Person { get; set; }
        public List<AddressViewModel> Address { get; set; }
    }
}

My test cshtml

@model Net5_MVC.Models.FamilyViewModel
@{
    ViewData["Title"] = "https://stackoverflow.com/questions/71086541/save-multiple-records-of-same-model-in-asp-net-5";
    int personcount = 3;
    int addresscount = 1;
    string AddressID = Guid.NewGuid().ToString();
}

<form asp-controller="Home" asp-action="SaveDetails" method="post">
    <br /><br />
    <h3>Person Area</h3>
    @for (int i = 0; i < personcount; i++)
    {
        <input asp-for="Person[i].AddressID" value="@AddressID" hidden="hidden" />
        <div class="row">
            <div class="col">
                <label asp-for=" Person[i].FirstName"></label>
                <input asp-for="Person[i].FirstName" />
            </div>
            <div class="col">
                <label asp-for="Person[i].LastName"></label>
                <input asp-for="Person[i].LastName" />
            </div>
        </div>
        <div class="row" id="">
            <div class="col">
                <label asp-for="Person[i].Email"></label>
                <input asp-for="Person[i].Email" />
            </div>
            <div class="col">
                <label asp-for="Person[i].CellNumber"></label>
                <input asp-for="Person[i].CellNumber" />
            </div>
        </div>
        <hr />
    }

    <h3>Address Area</h3>
    @for (int i = 0; i < addresscount; i++)
    {
        <input asp-for="Address[i].ID" value="@AddressID"  hidden="hidden" />
        <div class="row">
            <div class="col">
                <label asp-for="Address[i].StreetName"></label>
                <input asp-for="Address[i].StreetName" />
            </div>
            <div class="col">
                <label asp-for="Address[i].City"></label>
                <input asp-for="Address[i].City" />
            </div>
        </div>
        <div class="row">
            <div class="col">
                <label asp-for="Address[i].PostalCode"></label>
                <input asp-for="Address[i].PostalCode" />
            </div>
        </div>
        <hr />
    }

    <div><br /><br /></div>
    <div class="row">
        <div class="col-sm-3">
            <a class="btn btn-primary" id="addMore">Add More Member of Group</a>
        </div>
        <div class="col-sm-3">
            <button class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>

Test Method

[HttpPost]
public IActionResult SaveDetails(FamilyViewModel familyViewModel)
{
    List<PersonViewModel> personlist = familyViewModel.Person;
    List<AddressViewModel> addresslist = familyViewModel.Address;
    return Ok();
}

Test Result


问:
Docker driver "overlay2" failed to remove root filesystem: unlinkat - device or resource busy
When trying to remove a docker container (for example when trying to docker-compose down) I always get these errors:

```<code>ERROR: for <my_container>  container d8424f80ef124c2f3dd8f22a8fe8273f294e8e63954e7f318db93993458bac27: driver "overlay2" failed to remove root filesystem: unlinkat /var/lib/docker/overlay2/64311f2ee553a5d42291afa316db7aa392a29687ffa61971b4454a9be026b3c4/merged: device or resource busy
</code>```

Common advice like restarting the docker service, pruning or force removing the containers doesn't work. The only thing that I found that works is manually unmounting with sudo umount /home/virtfs/xxxxx/var/lib/docker/overlay2/<container_id>/merged, then I'm able to remove the container.

My OS is CentOS Linux release 7.9.2009 (Core) with kernel version 3.10.0-1127.19.1.el7.x86_64. I thought this was maybe due to overlay2 clashing with CentOS, but according to this page my CentOS/kernel version should work. It would be great to find a solution to this, because I ideally want to docker-compose down without having to use elevated privileges to umount beforehand.

答:
From the error log, it is observed that the file mounting is involved
Execute the following command to view the related processes

```<code>grep 64311f2ee553a5d42291afa316db7aa392a29687ffa61971b4454a9be026b3c4 /proc/*/mountinfo
</code>```
```<code>ps -ef | grep "The process ID obtained by the grep command above"
</code>```

Stop the occupied process

Then delete the container

Body:
When trying to remove a docker container (for example when trying to docker-compose down) I always get these errors:

ERROR: for <my_container>  container d8424f80ef124c2f3dd8f22a8fe8273f294e8e63954e7f318db93993458bac27: driver "overlay2" failed to remove root filesystem: unlinkat /var/lib/docker/overlay2/64311f2ee553a5d42291afa316db7aa392a29687ffa61971b4454a9be026b3c4/merged: device or resource busy

Common advice like restarting the docker service, pruning or force removing the containers doesn't work. The only thing that I found that works is manually unmounting with sudo umount /home/virtfs/xxxxx/var/lib/docker/overlay2/<container_id>/merged, then I'm able to remove the container.

My OS is CentOS Linux release 7.9.2009 (Core) with kernel version 3.10.0-1127.19.1.el7.x86_64. I thought this was maybe due to overlay2 clashing with CentOS, but according to this page my CentOS/kernel version should work. It would be great to find a solution to this, because I ideally want to docker-compose down without having to use elevated privileges to umount beforehand.

Body:
From the error log, it is observed that the file mounting is involved
Execute the following command to view the related processes

grep 64311f2ee553a5d42291afa316db7aa392a29687ffa61971b4454a9be026b3c4 /proc/*/mountinfo

ps -ef | grep "The process ID obtained by the grep command above"

Stop the occupied process

Then delete the container


问:
Fault Tolerance in Flink
How can we configure a Flink application to start/restart only the pods/(sub)tasks that crashed instead of restarting the whole job i.e. restart all the tasks/sub-tasks in the job/pipeline including that tasks that are healthy. It does not make sense and feels unnecessary to try to restart the healthy tasks along with the crashed ones. The stream processing application processes messages from Kafka and writes the output back to Kafka and runs on Flink 1.13.5 and a Kubernetes resource manager - using Lyft's Kubernetes operator to schedule and run the Flink job. We tried setting the property, **jobmanager.execution.failover-strategy** to **region** and did not help.

答:
Restart Pipelined Region Failover Strategy.

This strategy groups tasks into disjoint regions. When a task failure is detected, this strategy computes the smallest set of regions that must be restarted to recover from the failure. For some jobs this can result in fewer tasks that will be restarted compared to the Restart All Failover Strategy.

Refer to https://nightlies.apache.org/flink/flink-docs-master/docs/ops/state/task_failure_recovery/#restart-pipelined-region-failover-strategy

But another failover strategy is in progress in https://cwiki.apache.org/confluence/display/FLINK/FLIP-135+Approximate+Task-Local+Recovery

Approximate task-local recovery is useful in scenarios where a certain amount of data loss is tolerable, but a full pipeline restart is not affordable

Title: Fault Tolerance in Flink


问:
Log two model runs with Keras wandb
I am training multiple models in the same Colab notebook to compare some results. I've written a function to avoid repeating code, and I've added WandbCallback() in the list of callbacks for model_name.fit().

def generic_FE_trainer(model_name, checkpoint_filename, min_lr=1e-7):
    earlystop = callbacks.EarlyStopping(monitor="val_loss",
                                    patience=11,
                                    verbose=1)
    lr_reduction = callbacks.ReduceLROnPlateau(monitor='val_accuracy',
                                           patience=5,
                                           verbose=1,
                                           factor=0.8,
                                           min_lr=min_lr)
    checkpoint_dir = os.path.join(save_dir, checkpoint_filename)
    if not os.path.exists(checkpoint_dir):
        os.makedirs(checkpoint_dir)
    checkpoint = callbacks.ModelCheckpoint(filepath=os.path.join(checkpoint_dir, checkpoint_filename+'.h5'),
                                           monitor="val_loss",
                                           verbose=1,
                                           save_best_only=True,
                                           save_weights_only=False)
    return model_name.fit(train_gen,
                          epochs=40,
                          batch_size=4,
                          verbose=1,
                          callbacks=[earlystop, checkpoint, lr_reduction, WandbCallback()],
                          validation_data=val_gen)
```
<p>I call them with something like the code below, but then my project dashboard puts the data for both on the same graphs, where I've attached a graph for epochs (although it's not particularly useful) to show as an example.</p>
```history1 = generic_FE_trainer(model1, 'model1')
history2 = generic_FE_trainer(model2, 'model2')
```

This is the same for all my metrics, so how can I have wandb plot these graphs separately? I would like them to be in different runs, if that's possible.

答:
Use w = wandb.init() again to spawn a new process, and make sure to pass in reinit=True. The epochs are connected here because the first run never ends. To end a run, use w.finish().

So here, different runs would spawn with

w = wandb.init(reinit=True)
history1 = generic_FE_trainer(model1, 'model1')
w.finish()
wandb.init()
history2 = generic_FE_trainer(model2, 'model2')
```

Title: Log two model runs with Keras wandb

Body:
I am training multiple models in the same Colab notebook to compare some results. I've written a function to avoid repeating code, and I've added WandbCallback() in the list of callbacks for model_name.fit().

def generic_FE_trainer(model_name, checkpoint_filename, min_lr=1e-7):
    earlystop = callbacks.EarlyStopping(monitor="val_loss",
                                    patience=11,
                                    verbose=1)
    lr_reduction = callbacks.ReduceLROnPlateau(monitor='val_accuracy',
                                           patience=5,
                                           verbose=1,
                                           factor=0.8,
                                           min_lr=min_lr)
    checkpoint_dir = os.path.join(save_dir, checkpoint_filename)
    if not os.path.exists(checkpoint_dir):
        os.makedirs(checkpoint_dir)
    checkpoint = callbacks.ModelCheckpoint(filepath=os.path.join(checkpoint_dir, checkpoint_filename+'.h5'),
                                           monitor="val_loss",
                                           verbose=1,
                                           save_best_only=True,
                                           save_weights_only=False)
    return model_name.fit(train_gen,
                          epochs=40,
                          batch_size=4,
                          verbose=1,
                          callbacks=[earlystop, checkpoint, lr_reduction, WandbCallback()],
                          validation_data=val_gen)

I call them with something like the code below, but then my project dashboard puts the data for both on the same graphs, where I've attached a graph for epochs (although it's not particularly useful) to show as an example.

history1 = generic_FE_trainer(model1, 'model1')
history2 = generic_FE_trainer(model2, 'model2')

This is the same for all my metrics, so how can I have wandb plot these graphs separately? I would like them to be in different runs, if that's possible.


问:
Is it possible to use a variable containing column names as strings in expressions for creating new data.table columns
Is there an easy way to use a variable containing a data.table column name (string) in the right hand size of an expression that creates a new data.table column?

library(data.table)
mtcars = as.data.table(mtcars)

# Say I have the name of a data.table column stored in a variable
colname = "mpg"

# How could i use this variable to create new columns
# My initial attempt:
mtcars[, `:=` (xMPGBiggerThan20 = colname > 20)]

# I think result is based on "mpg" > 20, rather than using the column values
head(mtcars)
#>     mpg cyl disp  hp drat    wt  qsec vs am gear carb xMPGBiggerThan20
#> 1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4             TRUE
#> 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4             TRUE
#> 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1             TRUE
#> 4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1             TRUE
#> 5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2             TRUE
#> 6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1             TRUE

# How would I make the command equivalent to if I wrote
mtcars[, `:=` (xMPGBiggerThan20 = mpg > 20)]

# Desired result
head(mtcars)
#>     mpg cyl disp  hp drat    wt  qsec vs am gear carb xMPGBiggerThan20
#> 1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4             TRUE
#> 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4             TRUE
#> 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1             TRUE
#> 4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1             TRUE
#> 5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2            FALSE
#> 6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1            FALSE
```

Created on 2022-02-14 by the reprex package (v2.0.1)

答:
Here is some code that should work

```<code>mtcars[["xMPGBiggerThan20"]] <- mtcars[[colname]] > 20
</code>```

The following also produces an identical result

```<code>mtcars$xMPGBiggerThan20 <- mtcars[[colname]] > 20
</code>```

Body:
Is there an easy way to use a variable containing a data.table column name (string) in the right hand size of an expression that creates a new data.table column?

library(data.table)
mtcars = as.data.table(mtcars)

# Say I have the name of a data.table column stored in a variable
colname = "mpg"

# How could i use this variable to create new columns
# My initial attempt:
mtcars[, `:=` (xMPGBiggerThan20 = colname > 20)]

# I think result is based on "mpg" > 20, rather than using the column values
head(mtcars)
#>     mpg cyl disp  hp drat    wt  qsec vs am gear carb xMPGBiggerThan20
#> 1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4             TRUE
#> 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4             TRUE
#> 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1             TRUE
#> 4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1             TRUE
#> 5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2             TRUE
#> 6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1             TRUE

# How would I make the command equivalent to if I wrote
mtcars[, `:=` (xMPGBiggerThan20 = mpg > 20)]

# Desired result
head(mtcars)
#>     mpg cyl disp  hp drat    wt  qsec vs am gear carb xMPGBiggerThan20
#> 1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4             TRUE
#> 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4             TRUE
#> 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1             TRUE
#> 4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1             TRUE
#> 5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2            FALSE
#> 6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1            FALSE

Created on 2022-02-14 by the reprex package (v2.0.1)

Body:
Here is some code that should work

mtcars[["xMPGBiggerThan20"]] <- mtcars[[colname]] > 20

The following also produces an identical result

mtcars$xMPGBiggerThan20 <- mtcars[[colname]] > 20


问:
Can i expose multiple docker containers behind nat to be accessible from the web
I have a single static ip and want to know if it is possible to run several containers (lets say with ssh and apache) and let them be accessible from outside my local network by using my public ip. I tried it by using bind9 but dont think that works because i only have 1 ip address.

Some kind of router which connects based on a hostname or something for example?

I ended up using kubernetes with a clusterIP and nodePort service.

答: The docker -p parameter can map multiple different SSH or Apache ports


问:
How to read file from Visual Studio solution/project?
```<code> FileInfo template = new  FileInfo(@"C:\Users\bryan\Desktop\ReportTemplate.xlsx");
 template.IsReadOnly = false;
</code>```

This is fine for test, but I have the ReportTemplate.xlsx inside of my project solution. How can I use that file instead of a local one on my desktop? How do I reference the file inside the solution?

答:
You want to use Server.MapPath();

Make sure the file you want has been added to the project: File->Add Existing

```<code>FileInfo template = new  FileInfo(Server.MapPath("~/Directory/ReportTemplate.xlsx");
template.IsReadOnly = false;
</code>```

The ~ represents "root" of the project.

I think this will only work with ASP.NET.

ContentLicense: CC BY-SA 3.0

Body:
 FileInfo template = new  FileInfo(@"C:\Users\bryan\Desktop\ReportTemplate.xlsx");
 template.IsReadOnly = false;

This is fine for test, but I have the ReportTemplate.xlsx inside of my project solution. How can I use that file instead of a local one on my desktop? How do I reference the file inside the solution?

Body:
You want to use Server.MapPath();

Make sure the file you want has been added to the project: File->Add Existing

FileInfo template = new  FileInfo(Server.MapPath("~/Directory/ReportTemplate.xlsx");
template.IsReadOnly = false;

The ~ represents "root" of the project.

I think this will only work with ASP.NET.


问:
Looping through and comparing values in different dataframes
I have two dataframes:

df1:

Lower
Upper
Rank

0
7
first

8
14
second

15
23
third

df2:

Score

5

3

8

13

20

I want a third result dataframe df3 such that if the score in df2 is between the lower and upper values of df1, that row gets assigned the corresponding rank from df1

Score
Rank

5
first

3
first

8
second

13
second

20
third

答:
Try this.</p>
```<code>df1 = pd.DataFrame( [[0,7,'first'],[8,14,'second'],[15,23,'third']], columns = ['Lower', 'Upper', 'Rank'])
df2 = pd.DataFrame( [5,3,8,13,20], columns = ['Score'])

result = []
for index, val in df2.iterrows():
    for id, rank in df1.iterrows():
        if val['Score'] >= rank['Lower'] and val['Score'] <= rank['Upper']:
            result.append(rank['Rank'])
            break

df_result = pd.DataFrame(columns = ['Score','Rank'])
df_result['Score'] = df2['Score']
df_result['Rank'] = result
</code>```

Body:
Try this.

df1 = pd.DataFrame( [[0,7,'first'],[8,14,'second'],[15,23,'third']], columns = ['Lower', 'Upper', 'Rank'])
df2 = pd.DataFrame( [5,3,8,13,20], columns = ['Score'])

result = []
for index, val in df2.iterrows():
    for id, rank in df1.iterrows():
        if val['Score'] >= rank['Lower'] and val['Score'] <= rank['Upper']:
            result.append(rank['Rank'])
            break

df_result = pd.DataFrame(columns = ['Score','Rank'])
df_result['Score'] = df2['Score']
df_result['Rank'] = result


问:
Flutter DateTime.now is showing wrong time on real device
I am showing DateTime.now(); on the time picker in my app but its showing me wrong time. I have printed out timezone it shows CET but when I put .toLocal it shown the correct device time but .toLocal isnt working with put on DateTime.now().toLocal(), like this it still gives wrong time like 23 : 39 even when current time is 00: 20. What I am looking forward to is I want the correct local time/device time to be tracked by the app because I don't the user to select past time. Point to be noted I want the time in 24h standard and if to be specific what timezone I want so that is GMT+1

Here's my code so far for this functionality.

```<code>TimePickerSpinner(
                      is24HourMode: true,
                      isForce2Digits: true,
                      alignment: Alignment.center,
                      normalTextStyle: TextStyle(
                        fontSize: 14,
                        color: Colors.white,
                      ),
                      highlightedTextStyle:
                          TextStyle(fontSize: 16, color: Colors.black),
                      time: DateTime.now(),
                      onTimeChange: (time) {
                        DateFormat formatHour = DateFormat("HH");
                        String nowTimeHour = formatHour.format(DateTime.now());
                        String selectedTimeHour = formatHour.format(time);
                        DateFormat formatMints = DateFormat("mm");
                        String nowTimeMints =
                            formatMints.format(DateTime.now());
                        String selectedTimeMints = formatMints.format(time);
                        print(int.parse(nowTimeHour));
                        print(int.parse(selectedTimeHour));
                        if (int.parse(nowTimeHour) >
                            int.parse(selectedTimeHour)) {
                          setState(() {
                            isTimeCorrent = true;
                          });
                        } else if (int.parse(nowTimeHour) ==
                                int.parse(selectedTimeHour) &&
                            int.parse(nowTimeMints) >
                                int.parse(selectedTimeMints)) {
                          setState(() {
                            isTimeCorrent = true;
                          });
                        } else {
                          setState(() {
                            dateTimeSelected = time;
                            isTimeCorrent = false;
                          });
                        }
                      },
                    ),
</code>```

答:
```<code>  var date = DateTime.now().toUtc();
</code>```

This will give universal time .so adding or subtracting gmt time get you time.(here Gmt+1 so add 1 hour to the utc time get the correct time)

```<code>  var date = DateTime.now().toUtc().add(Duration(hours:1));
</code>```

here add  Hours 1 => Gmt +1 represent utc time + hours

Body:
I am showing DateTime.now(); on the time picker in my app but its showing me wrong time. I have printed out timezone it shows CET but when I put .toLocal it shown the correct device time but .toLocal isnt working with put on DateTime.now().toLocal(), like this it still gives wrong time like 23 : 39 even when current time is 00: 20. What I am looking forward to is I want the correct local time/device time to be tracked by the app because I don't the user to select past time. Point to be noted I want the time in 24h standard and if to be specific what timezone I want so that is GMT+1

Here's my code so far for this functionality.

TimePickerSpinner(
                      is24HourMode: true,
                      isForce2Digits: true,
                      alignment: Alignment.center,
                      normalTextStyle: TextStyle(
                        fontSize: 14,
                        color: Colors.white,
                      ),
                      highlightedTextStyle:
                          TextStyle(fontSize: 16, color: Colors.black),
                      time: DateTime.now(),
                      onTimeChange: (time) {
                        DateFormat formatHour = DateFormat("HH");
                        String nowTimeHour = formatHour.format(DateTime.now());
                        String selectedTimeHour = formatHour.format(time);
                        DateFormat formatMints = DateFormat("mm");
                        String nowTimeMints =
                            formatMints.format(DateTime.now());
                        String selectedTimeMints = formatMints.format(time);
                        print(int.parse(nowTimeHour));
                        print(int.parse(selectedTimeHour));
                        if (int.parse(nowTimeHour) >
                            int.parse(selectedTimeHour)) {
                          setState(() {
                            isTimeCorrent = true;
                          });
                        } else if (int.parse(nowTimeHour) ==
                                int.parse(selectedTimeHour) &&
                            int.parse(nowTimeMints) >
                                int.parse(selectedTimeMints)) {
                          setState(() {
                            isTimeCorrent = true;
                          });
                        } else {
                          setState(() {
                            dateTimeSelected = time;
                            isTimeCorrent = false;
                          });
                        }
                      },
                    ),

Body:
  var date = DateTime.now().toUtc();

This will give universal time .so adding or subtracting gmt time get you time.(here Gmt+1 so add 1 hour to the utc time get the correct time)

  var date = DateTime.now().toUtc().add(Duration(hours:1));

here add  Hours 1 => Gmt +1 represent utc time + hours


问:
Xamarin listview change color
How do change the color of the specific item in the listview?
Ex( a listview of user that has status of active and inactive)

The active item background or border color will be set to green and inactive as red.

答:
From my point of view, the easiest way is to change color of selected ViewCell using view cell tapped event as below:

```<code>  public partial class PageList : ContentPage
{
    ViewCell lastCell;
    public PageList()
    {
        InitializeComponent();

        listView.ItemsSource = new List<Contact>
        {
           new Contact { Name = "JP Morgan"},
           new Contact { Name ="Andrew Carnegie"},
           new Contact{ Name="Steve Jobs"}
        };
    }

    private void ViewCell_Tapped(object sender, EventArgs e)
    {
        if (lastCell != null)
            lastCell.View.BackgroundColor = Color.Red;
        var viewCell = (ViewCell)sender;
        if (viewCell.View != null)
        {
            viewCell.View.BackgroundColor = Color.Green;
            lastCell = viewCell;
        }
    }
}
</code>```

Below is the listview in xaml,note that I set the background color of stacklayout to red as this is the default inactive color.

```<code>   <ListView x:Name="listView"
              SeparatorColor="Aqua">
            <ListView.ItemTemplate>
                <DataTemplate >
                    <ViewCell  Tapped="ViewCell_Tapped" >
                        <StackLayout  Background="red">
                            <Label Text="{Binding Name}"></Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
    </ListView>
</code>```

Title: Xamarin listview change color

Body:
From my point of view, the easiest way is to change color of selected ViewCell using view cell tapped event as below:

  public partial class PageList : ContentPage
{
    ViewCell lastCell;
    public PageList()
    {
        InitializeComponent();

        listView.ItemsSource = new List<Contact>
        {
           new Contact { Name = "JP Morgan"},
           new Contact { Name ="Andrew Carnegie"},
           new Contact{ Name="Steve Jobs"}
        };
    }

    private void ViewCell_Tapped(object sender, EventArgs e)
    {
        if (lastCell != null)
            lastCell.View.BackgroundColor = Color.Red;
        var viewCell = (ViewCell)sender;
        if (viewCell.View != null)
        {
            viewCell.View.BackgroundColor = Color.Green;
            lastCell = viewCell;
        }
    }
}

Below is the listview in xaml,note that I set the background color of stacklayout to red as this is the default inactive color.

   <ListView x:Name="listView"
              SeparatorColor="Aqua">
            <ListView.ItemTemplate>
                <DataTemplate >
                    <ViewCell  Tapped="ViewCell_Tapped" >
                        <StackLayout  Background="red">
                            <Label Text="{Binding Name}"></Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
    </ListView>


问:
Problem with background location settings using NSUserDefaults
I am storing Location settings in the settings bundle. So when I flip a switch to NO, my app stops the background location service.

I am using an observer to detect settings change, and updating a flag in my app. The problem is, if  I flip the switch to OFF, my app does not stop the location service till I open the app. This is understandable, since my observer resides in the source code. Is there a way to listen for the settings while the app is in the background? I am an iOS development newbie, so I do not understand the concept of background and foreground so much.

答: Its not possible is what I found.</p>

Body: Its not possible is what I found.


问:
How to check if array contains other array objects [JS]
I'm trying to make a basic javascript algorithim. Im trying to make a basic 'enjoyability' scale.
Basically if the array "tags", contains an object from "interests" add 1 to enjoyability. If the array "tags" contains an object from "dislikes" subtract 1 from enjoyability.
How can I do this?

const fs = require('fs');
var interests = ["gaming", "coding", "dogs", "food"];
var dislikes = ["cats", "school", "work", "politics"];
var tags = ["gaming", "dogs", "school", "food", "coding"];
var enjoyability = 0;
var enjoyable = 0;
var PosOrNeg = 0;
var isIn;
const intr = tags.some(r=> interests.indexOf(r) >= 4)
const disl = tags.some(r=> dislikes.indexOf(r) >= 0)

if (intr == true) {
    console.log('a')
}

function run() {

console.log('a'+enjoyability)
    console.log(tags.includes())
    if (enjoyability >= 0) {
        enjoyable = 0;
        console.log("yes")
    } else {
        enjoyable < 0;
        console.log("no")
    }
}
console.log(intr)
console.log(disl)
console.log(enjoyable)
run()
```

答:
Perhaps this will help you:</p>
```<code>var interests = ["gaming", "coding", "dogs", "food"];
var dislikes = ["cats", "school", "work", "politics"];
var tags = ["gaming", "dogs", "school", "food", "coding"];

function run() {
  var enjoyability = 0;
  for (let i = 0; i < tags.length; i++) {
    const element = tags[i];

    if (interests.includes(element)) {
      enjoyability++ // Add one
    } else if (dislikes.includes(element)) {
      enjoyability--; // Subtract one
    }
  }

  return enjoyability;
}

const output = run();

console.log(output);
</code>```

Body:
Perhaps this will help you:

var interests = ["gaming", "coding", "dogs", "food"];
var dislikes = ["cats", "school", "work", "politics"];
var tags = ["gaming", "dogs", "school", "food", "coding"];

function run() {
  var enjoyability = 0;
  for (let i = 0; i < tags.length; i++) {
    const element = tags[i];

    if (interests.includes(element)) {
      enjoyability++ // Add one
    } else if (dislikes.includes(element)) {
      enjoyability--; // Subtract one
    }
  }

  return enjoyability;
}

const output = run();

console.log(output);


问:
Caused by: IllegalArgumentException: Wrong basePath for the root path [Spark]
I want to read a stream of the parquet files

```<code>    val df: DataFrame = spark
      .readStream
      .option("maxFilesPerTrigger", 1)
      .schema(schema)
      .parquet("D:/Programming/Scala/ScalaMaven/parquet1")
</code>```

but I`m getting this error

```<code>java.lang.IllegalArgumentException: Wrong basePath D:/path-to-the-folder-whith-parquet-files/parquet1 for the root path: file:/D:/another-path/parquet/part-00013-f3846a4a-2177-4a24-a7e1-3e20a898b4a6-c000.snappy.parquet
</code>```

I just saw the interesting thing in the logs

```<code>22/02/14 09:37:21 WARN HadoopFSUtils: The directory file:/D:/another-path/parquet/part-00013-f3846a4a-2177-4a24-a7e1-3e20a898b4a6-c000.snappy.parquet was not found. Was it deleted very recently?
</code>```

Help me I`m stuck

答:
Try</p>
```<code>val df: DataFrame = spark
      .readStream
      .option("maxFilesPerTrigger", 1)
      .schema(schema)
      .parquet("file:///d:/Programming/Scala/ScalaMaven/parquet1")
</code>```

Body:
I want to read a stream of the parquet files

    val df: DataFrame = spark
      .readStream
      .option("maxFilesPerTrigger", 1)
      .schema(schema)
      .parquet("D:/Programming/Scala/ScalaMaven/parquet1")

but I`m getting this error

java.lang.IllegalArgumentException: Wrong basePath D:/path-to-the-folder-whith-parquet-files/parquet1 for the root path: file:/D:/another-path/parquet/part-00013-f3846a4a-2177-4a24-a7e1-3e20a898b4a6-c000.snappy.parquet

I just saw the interesting thing in the logs

22/02/14 09:37:21 WARN HadoopFSUtils: The directory file:/D:/another-path/parquet/part-00013-f3846a4a-2177-4a24-a7e1-3e20a898b4a6-c000.snappy.parquet was not found. Was it deleted very recently?

Help me I`m stuck

Body:
Try

val df: DataFrame = spark
      .readStream
      .option("maxFilesPerTrigger", 1)
      .schema(schema)
      .parquet("file:///d:/Programming/Scala/ScalaMaven/parquet1")


问:
Does Presto SQL support recursive query using CTE just like SQL Server? e.g. employee hierarchy level
I want to write a recursive query using CTE in Presto to find Employee Hierarchy. Do Presto support recursive query?
When I write simple recursion as

with cte as(select 1 n
           union all
           select cte.n+1 from cte where n<50)
select * from cte

It gives error that

Error running query: line 3:32: Table cte does not exist

答:
```<code>WITH RECURSIVE cte(n) AS (
    SELECT 1
    UNION ALL
    SELECT n + 1 FROM cte WHERE n < 50)
SELECT * from cte
</code>```

Error : Recursion depth limit exceeded (10)

adjust max_recursion_depth

Body:
WITH RECURSIVE cte(n) AS (
    SELECT 1
    UNION ALL
    SELECT n + 1 FROM cte WHERE n < 50)
SELECT * from cte

Error : Recursion depth limit exceeded (10)

adjust max_recursion_depth


问:
Fable.Reactstrap not defined on Client fsproj SATE-stack
I'm trying to use Fable.Reactstrap on Client project from SAFE.Template. I've added Fable.Reactstrap to Nuget, Paket, and NPM but still receive error FSHARP: The namespace 'Reactstrap' is not defined when executing dotnet run. It's an error from code:

```<code>open Fable.Reactstrap
</code>```

The real code can be found on my github's repo. Fable.Reactstrap itself has been added to project's dependencies and added in paket.references.

How can I resolve this error and user Fable.Reactstrap in my project?

答:
The namespace is just Reactstrap, so this should work:

open Reactstrap
```

See example code here.

Body:
I'm trying to use Fable.Reactstrap on Client project from SAFE.Template. I've added Fable.Reactstrap to Nuget, Paket, and NPM but still receive error FSHARP: The namespace 'Reactstrap' is not defined when executing dotnet run. It's an error from code:

open Fable.Reactstrap

The real code can be found on my github's repo. Fable.Reactstrap itself has been added to project's dependencies and added in paket.references.

How can I resolve this error and user Fable.Reactstrap in my project?

Body:
The namespace is just Reactstrap, so this should work:

open Reactstrap

See example code here.


问:
Passing Variable from JS to VB.net
I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.

I have tried putting the variable into a label then  grabbing it from the label in vb.net  as shown in the code below:

Js part.

```<code>document.getElementById("Label1").innerText = nwLat;
</code>```

then in the vb part

```<code>   Dim nwLat As Double
    nwLat = Label1.Text
    MsgBox(nwLat)
</code>```

it does not work for me any ideas? the error that comes up is
 Input string was not in a correct format.

Cheers!

答:
In JavaScript:

```<code>__doPostBack(
    'edit',
    JSON.stringify({ ID: id, Code: code, AcctNo: acctNo })
);
</code>```

In VB.NET:

```<code>Protected Sub Page_Load(s As Object, e As EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        '...
    Else
        Dim eventTarget As String = Request.Form!__EVENTTARGET
        Dim eventArgument As String = Request.Form!__EVENTARGUMENT
        If Not eventArgument Is Nothing AndAlso Not eventTarget Is Nothing AndAlso eventTarget = "edit" Then
            Dim jss As New JavaScriptSerializer()
            Dim ac As AccountCode = jss.Deserialize(Of AccountCode)(eventArgument)
        End If
    End If
End Sub
</code>```

Title: Passing Variable from JS to VB.net

Body:
I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.

I have tried putting the variable into a label then  grabbing it from the label in vb.net  as shown in the code below:

Js part.

document.getElementById("Label1").innerText = nwLat;

then in the vb part

   Dim nwLat As Double
    nwLat = Label1.Text
    MsgBox(nwLat)

it does not work for me any ideas? the error that comes up is
 Input string was not in a correct format.

Cheers!

Body:
In JavaScript:

__doPostBack(
    'edit',
    JSON.stringify({ ID: id, Code: code, AcctNo: acctNo })
);

In VB.NET:

Protected Sub Page_Load(s As Object, e As EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        '...
    Else
        Dim eventTarget As String = Request.Form!__EVENTTARGET
        Dim eventArgument As String = Request.Form!__EVENTARGUMENT
        If Not eventArgument Is Nothing AndAlso Not eventTarget Is Nothing AndAlso eventTarget = "edit" Then
            Dim jss As New JavaScriptSerializer()
            Dim ac As AccountCode = jss.Deserialize(Of AccountCode)(eventArgument)
        End If
    End If
End Sub


问:
DPDK l2fwd - How to forward ethernet interface to my PMD
I have a board with one ethernet interface (eth0) running Linux.
I'm trying to forward all incoming traffic from eth0 to my PMD driver, using dpdk-l2fwd example application.

Here is what I've tried:

```<code>./dpdk-l2fwd -c 0x3 --vdev={my_pmd}0 -- -p 0x3 -T 0
</code>```

I can see that my rx_pkt_burst callback is polled by the application, but that's it.

How can I forward all incoming eth0 packets to my PMD?

I tried to use net_tap, using the following command:

```<code>./dpdk-l2fwd -c 0xff --vdev=net_tap0 --vdev={my_pmd}0 -- -p 0x7 -T 0 --portmap="(1,2)"
</code>```

And my tx_pkt_burst callback is called occasionally, but not when I think it should be called.
For example, if I ping this board from another one, the ping is successful, but the tx_pkt_burst callback is not been called.

I tried to use devbind tool, but no devices are detected:

```<code>./usertools/dpdk-devbind.py --status

No 'Network' devices detected
=============================

No 'Baseband' devices detected
==============================

No 'Crypto' devices detected
============================

No 'Eventdev' devices detected
==============================

No 'Mempool' devices detected
=============================

No 'Compress' devices detected
==============================

No 'Misc (rawdev)' devices detected
===================================

No 'Regex' devices detected
===========================
</code>```

Update

DPDK version - 20.11.

My HW is a embedded device based on NXP's Layerscape.

```<code>$ lshw -class network
  *-network
       description: Ethernet interface
       physical id: 3
       logical name: eth0
       serial: 00:11:22:44:11:44
       size: 1Gbit/s
       capacity: 1Gbit/s
       capabilities: ethernet physical tp mii 10bt-fd 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=fsl_dpaa2_eth driverversion=5.10.35-00002-g3434eea0e1e7-dir duplex=full firmware=7.17 ip=192.168.15.157 link=yes multicast=yes port=twisted pair speed=1Gbit/s
</code>```

I'm trying to bypass all traffic to the PMD I'm currently developing.

Thanks.

答:
[EDIT-1] clarification of using same interface for DPDK and Kernel routing

Answer> as discussed over comments please refer to DPDKD + kernel on same interface

Based on the information shared there are multiple questions to the single query I'm trying to bypass all traffic to the PMD I'm currently developing. Addressing each one separately below

question 1: using dpdk-l2fwd example application

Answer> DPDK application l2fwd application makes use of basic APi with almost no HW offloads. Based on your environment (I have a board with one ethernet interface (eth0)), the right set of parameters should be -p 0x1 --no-mac-updating -T 1. This will configure the application to receive and transmit packet using single DPDK interface (that is eth0 on your board).

Note: DPDK Application can work with DPDK PMD both physical and virtual

question 2: I tried to use net_tap, using the following command:

Answer> If the intend is to intercept the traffic from physical and then forward to tap interface, then one needs modify the eal arguments as ./build/l2fwd --vdev=net_tap0,iface="my_eth0" -- -p 0x3 -T 1 --no-mac-updating. This will allow the application to probe physical NXP interface (eth0) and make use of Linux TAP interface as secondary interface. Thus any traffic from NXP and TAP will be cross connected such as NXP (eth0) <==> TAP (my_eth0)

question 3: ./usertools/dpdk-devbind.py --status returns empty

Answer> Form the dpdk site supported NIC list NXP dpaa, dpaa2, enetc, enetfec, pfe. Cross checking the kernel driver fsl_dpaa2_eth  I think it is safe to assume  dpaa2 PMD is supported. As you have mentioned the NIC is not enumerated, it looks like there are certain caveats to such model revision, supported board, BSP package, vendor-sub vendor ID check etc. More details can be found Board Support Package, and DPAA2 NIC guide

Debug & Alternative solutions:

To start with use the Kernel Driver to bring in packets

Use extra logging and debug to identify why the NIC is shown in the application

Approach 1:

Make sure the NIC is bind with kernel driver fsl_dpaa2_eth.

ensure NIC is connected and link is up with ethtool eth0

set to promiscous mode with ifconfig eth0 promisc up

start DPDK application with PCAP PMD, ./build/l2fwd --vdev=net_pcap0,iface=eth0 -- -p 1 --no-mac-updating -T 1

Check packet are received and redirected to PCAP eth0 PMD by checking the statistics.

Approach 2:

Ideally the NIC should be categorized under network device to be probed by debind.py.

Check the device details using lshw -c net -businfo for network.

try checking with lspci -Dvmmnnk [PCIe BUS:Slot:Function id] for network details.

If above details does not show up as network device this might be reason for not getting listed.

Suggestions or workaround: You can try to forcefully bind with igb_uio or vfio-pci (I am not much famialr with NXP SoC) by dpdk-devbind -b vfio-pci [PCIe S:B:F]. Then cross check with lspci -ks [PCIe S:B:F]. Once successfully done, one can start dpdk l2fwd in PMD debug mode with ./build/l2fwd -a [PCIe S:B:F] --log-level=pmd,8 -- -p 1 --no-mac-updating | more. Thus by intercepting and interpreting the logs one can identify what is going

Note:

It is assumed the application is build with static libraries and not dynamic. To build with static libraries use make static for l2fwd.

For the described use case recommended application is basicfwd/skeleton rather than l2fwd.

Body:
I have a board with one ethernet interface (eth0) running Linux.
I'm trying to forward all incoming traffic from eth0 to my PMD driver, using dpdk-l2fwd example application.

Here is what I've tried:

./dpdk-l2fwd -c 0x3 --vdev={my_pmd}0 -- -p 0x3 -T 0

I can see that my rx_pkt_burst callback is polled by the application, but that's it.

How can I forward all incoming eth0 packets to my PMD?

I tried to use net_tap, using the following command:

./dpdk-l2fwd -c 0xff --vdev=net_tap0 --vdev={my_pmd}0 -- -p 0x7 -T 0 --portmap="(1,2)"

And my tx_pkt_burst callback is called occasionally, but not when I think it should be called.
For example, if I ping this board from another one, the ping is successful, but the tx_pkt_burst callback is not been called.

I tried to use devbind tool, but no devices are detected:

./usertools/dpdk-devbind.py --status

No 'Network' devices detected
=============================

No 'Baseband' devices detected
==============================

No 'Crypto' devices detected
============================

No 'Eventdev' devices detected
==============================

No 'Mempool' devices detected
=============================

No 'Compress' devices detected
==============================

No 'Misc (rawdev)' devices detected
===================================

No 'Regex' devices detected
===========================

Update

DPDK version - 20.11.

My HW is a embedded device based on NXP's Layerscape.

$ lshw -class network
  *-network
       description: Ethernet interface
       physical id: 3
       logical name: eth0
       serial: 00:11:22:44:11:44
       size: 1Gbit/s
       capacity: 1Gbit/s
       capabilities: ethernet physical tp mii 10bt-fd 100bt-fd 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=fsl_dpaa2_eth driverversion=5.10.35-00002-g3434eea0e1e7-dir duplex=full firmware=7.17 ip=192.168.15.157 link=yes multicast=yes port=twisted pair speed=1Gbit/s

I'm trying to bypass all traffic to the PMD I'm currently developing.

Thanks.


问:
ordering = ['-created'] what it means in Django? why we use - sign in ordering?
Below is my code.

```<code>class Basecalss(models.Model):
   title = models.CharField(max_length=255)
   created = models.DateTimeField(auto_now_add=True)
   update = models.DateTimeField(auto_now=True)

   class Meta:
      abstract = True
      ordering = ['-created']
</code>```

Here why we use - sing before created, what it means??

答:
A leading negative sign indicates descending order.

So "created" would be oldest first (ascending), and "-created" would indicate newest first.

This is documented under querysets.

Body:
Below is my code.

class Basecalss(models.Model):
   title = models.CharField(max_length=255)
   created = models.DateTimeField(auto_now_add=True)
   update = models.DateTimeField(auto_now=True)

   class Meta:
      abstract = True
      ordering = ['-created']

Here why we use - sing before created, what it means??


问:
How to check if database exists in Cosmos DB?
I am trying to use the Cosmos DB .NET client to write some code that would clear existing Cosmos database and create a new structure. I want to delete a database with the specified name so that all its collections are gone and then create a new one. However I don't see a way to cleanly check if the database exists. There is the CreateIfNotExists method but this is not what I want. I want to remove the existing database. The only way I can think of is to catch the CosmosException and check for 404 status code but it seems like there should be some API to check for existence or some result object.</p>

答:
I Created a method to check if the database exists.</p>
```<code>    /// <summary>
    /// Checks if a database exists.
    /// </summary>
    /// <param name="databaseName">Name of the database to check.</param>
    /// <returns>True, if the database exists, otherwise false.</returns>
    public async Task<bool> DatabaseExistsAsync(string databaseName)
    {
        var databaseNames = new List<string>();
        using (FeedIterator<DatabaseProperties> iterator = cosmosClient.GetDatabaseQueryIterator<DatabaseProperties>())
        {
            while (iterator.HasMoreResults)
            {
                foreach (DatabaseProperties databaseProperties in await iterator.ReadNextAsync())
                {
                    databaseNames.Add(databaseProperties.Id);
                }
            }
        }

        return databaseNames.Contains(databaseName);
    }

    /// <summary>
    /// Checks if a container exists.
    /// </summary>
    /// <param name="containerName">Name of the container to check.</param>
    /// <returns>True, if the container exists, otherwise false.</returns>
    public async Task<bool> ContainerExistsAsync(string databaseName, string containerName)
    {
        var databaseExists = await this.DatabaseExistsAsync(databaseName);
        if (!databaseExists)
        {
            return false;
        }

        var containerNames = new List<string>();
        var database = this.cosmosClient.GetDatabase(databaseName);
        using (FeedIterator<ContainerProperties> iterator = database.GetContainerQueryIterator<ContainerProperties>())
        {
            while (iterator.HasMoreResults)
            {
                foreach (ContainerProperties containerProperties in await iterator.ReadNextAsync())
                {
                    containerNames.Add(containerProperties.Id);
                }
            }
        }

        return containerNames.Contains(containerName);
    }
</code>```

Body:
I Created a method to check if the database exists.

    /// <summary>
    /// Checks if a database exists.
    /// </summary>
    /// <param name="databaseName">Name of the database to check.</param>
    /// <returns>True, if the database exists, otherwise false.</returns>
    public async Task<bool> DatabaseExistsAsync(string databaseName)
    {
        var databaseNames = new List<string>();
        using (FeedIterator<DatabaseProperties> iterator = cosmosClient.GetDatabaseQueryIterator<DatabaseProperties>())
        {
            while (iterator.HasMoreResults)
            {
                foreach (DatabaseProperties databaseProperties in await iterator.ReadNextAsync())
                {
                    databaseNames.Add(databaseProperties.Id);
                }
            }
        }

        return databaseNames.Contains(databaseName);
    }

    /// <summary>
    /// Checks if a container exists.
    /// </summary>
    /// <param name="containerName">Name of the container to check.</param>
    /// <returns>True, if the container exists, otherwise false.</returns>
    public async Task<bool> ContainerExistsAsync(string databaseName, string containerName)
    {
        var databaseExists = await this.DatabaseExistsAsync(databaseName);
        if (!databaseExists)
        {
            return false;
        }

        var containerNames = new List<string>();
        var database = this.cosmosClient.GetDatabase(databaseName);
        using (FeedIterator<ContainerProperties> iterator = database.GetContainerQueryIterator<ContainerProperties>())
        {
            while (iterator.HasMoreResults)
            {
                foreach (ContainerProperties containerProperties in await iterator.ReadNextAsync())
                {
                    containerNames.Add(containerProperties.Id);
                }
            }
        }

        return containerNames.Contains(containerName);
    }


问:
Show all commits in repository using git rebase
I am running git rebase HEAD~X and I can't see all of the commits on the text editor which opens after I run this command, I have 6 commits that appears when I run git log --all.

Running git rebase -i HEAD~2 shows only 2 to edit, I'm not able to run anything beyond HEAD~3, When I try, I get the error message:

fatal: invalid upstream 'HEAD~6'

I believe this is happening because I previously ran 'git reset'. How can I view all six commits in 'git rebase'?

Edit

I have one repository which contains only one branch called "main" and 6 commits since the beginning: https://github.com/DevEsteves/WebScrapingWithPython

答:
I want to see all of the 6 commits on git rebase

All you can see in an interactive rebase todo list is the parent chain starting at where you are now (HEAD). If some of those 6 commits are not your direct parent / ancestor, you will not see them in the list.

I have 6 commits that appears when I run git log --all

But that doesn't mean there are 6 ancestor commits between you and the start. Try

```<code>git log --all --oneline --decorate --graph
</code>```

for a better look at where you are.

That said, note that you can likely get one more commit into your interactive rebase todo list by saying

```<code>git rebase -i --root
</code>```

Body:
I want to see all of the 6 commits on git rebase

All you can see in an interactive rebase todo list is the parent chain starting at where you are now (HEAD). If some of those 6 commits are not your direct parent / ancestor, you will not see them in the list.

I have 6 commits that appears when I run git log --all

But that doesn't mean there are 6 ancestor commits between you and the start. Try

git log --all --oneline --decorate --graph

for a better look at where you are.

That said, note that you can likely get one more commit into your interactive rebase todo list by saying

git rebase -i --root