问:
How to pass data from functional component to class component
I am new to ReactJS and have created a functional component for user input data(date and select).
Another class component to invoke the APIs from the user input data. I need to pass the input values from functional component to class component.

Can you please help?

Below is the snippet for functional component with input fields. The setShowGetAPI is initially set to false and will be true once the user clicks submit button.Please let me know if the condition is correct

```<code>  const [showTable, setshowTable] = useState("hidetable");
const [showGetAPI, setShowGetAPI] = React.useState("false");

  const [startDate, setStartDate] = useState(false);
  const [endDate, setendDate] = useState(false);
  const [expenseType, setexpenseType] = useState(false);

const showMessage = () => {
    setshowTable("");
    setShowGetAPI("true");
  };

  debugger;
  const handleEndDate = (e) => {
    setendDate(e.target.value);
  };

  const handleStartDate = (e) => {
    setStartDate(e.target.value);
  };

  const handleType = (e) => {
    console.log(e.target.value);
    setexpenseType(e.target.value);
  };
  console.log(endDate);

  return (
    <div>
      <Navbar color="info" light expand="md">
        <Nav color="info" navbar>
          <NavItem className="hdr">
            <NavLink>API Demo Tool</NavLink>
          </NavItem>
        </Nav>
      </Navbar>
      <Nav tabs>
        <NavItem>
          <NavLink
            className={{ active: activeTab === "1" }}
            onClick={() => {
              toggle("1");
            }}
          >
            Request
          </NavLink>
        </NavItem>
        <NavItem>
          <NavLink
            className={{ active: activeTab === "2" }}
            onClick={() => {
              toggle("2");
            }}
          >
            Receipt
          </NavLink>
        </NavItem>
      </Nav>
      <TabContent activeTab={activeTab}>

        <TabPane tabId="2">
          <br />
          <Form>
            <FormGroup row>
              <Label for="Start Date" sm={1}>
                Start Date
              </Label>
              <Col sm={2}>
                <Input
                  type="date"
                  name="startDate"
                  id="startDate"
                  placeholder="startDate"
                  value={startDate}
                  onChange={handleStartDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>
              <Label for="End Date" sm={1}>
                End Date
              </Label>
              <Col sm={2}>
                <Input
                  type="date"
                  name="endDate"
                  id="endDate"
                  value={endDate}
                  placeholder="endDate"
                  onChange={handleEndDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>
              <Label for="Segment" sm={1}>
                Expense Type
              </Label>
              <Col sm={2}>
                <Input
                  type="select"
                  name="expenseType"
                  value={expenseType}
                  id=" expenseType"
                  onChange={handleType}
                >
                  <option>Hotel</option>
                  <option>Airfare</option>
                  <option>Rail</option>
                  <option>All</option>
                </Input>
              </Col>
            </FormGroup>
            <FormGroup check row>
              <Col sm={{ size: 10, offset: 1 }}>
                <Button onClick={showMessage}>Submit</Button>
              </Col>
            </FormGroup>
          </Form>
          <div>

            {showGetAPI == "true" && (
            <div>
              <GetAPI
                startDt={startDate}
                endDt={endDate}
                exptype={expenseType}
              />
            </div>
          )}
          </div>
          <div class={showTable}>
            <Table></Table>
          </div>
        </TabPane>
      </TabContent>
    </div>
  );
};

export default TabsDemo;
</code>```

GETAPI- This is a class component where i need the inputs values from above functional component to invoke the API with req. params

```<code>class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      ReportEntryID: [],
      token: null,
      Url: [
        {
          Url: "",
        },
      ],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
    return <h1> {this.props.startdate}</h1>;
  }
}

export default GetAPI;
</code>```

答:
your getApi component mount on first render of your parent component.
so, you have to check using componentDidUpdate in getApi component like this.

in your getApi component

```<code>componentDidUpdate = (prevProps) => {
  console.log('prevProps',prevProps);
  console.log('this props',this.props);
}
</code>```

check if your getting props or not ?
hope this will help.

Body:
I am new to ReactJS and have created a functional component for user input data(date and select).
Another class component to invoke the APIs from the user input data. I need to pass the input values from functional component to class component.

Can you please help?

Below is the snippet for functional component with input fields. The setShowGetAPI is initially set to false and will be true once the user clicks submit button.Please let me know if the condition is correct

  const [showTable, setshowTable] = useState("hidetable");
const [showGetAPI, setShowGetAPI] = React.useState("false");

  const [startDate, setStartDate] = useState(false);
  const [endDate, setendDate] = useState(false);
  const [expenseType, setexpenseType] = useState(false);

const showMessage = () => {
    setshowTable("");
    setShowGetAPI("true");
  };

  debugger;
  const handleEndDate = (e) => {
    setendDate(e.target.value);
  };

  const handleStartDate = (e) => {
    setStartDate(e.target.value);
  };

  const handleType = (e) => {
    console.log(e.target.value);
    setexpenseType(e.target.value);
  };
  console.log(endDate);

  return (

      <Navbar color="info" light expand="md">

          <NavItem className="hdr">
            <NavLink>API Demo Tool</NavLink>
          </NavItem>

      </Navbar>

        <NavItem>
          <NavLink
            className={{ active: activeTab === "1" }}
            onClick={() => {
              toggle("1");
            }}
          >
            Request
          </NavLink>
        </NavItem>
        <NavItem>
          <NavLink
            className={{ active: activeTab === "2" }}
            onClick={() => {
              toggle("2");
            }}
          >
            Receipt
          </NavLink>
        </NavItem>

      <TabContent activeTab={activeTab}>

        <TabPane tabId="2">

          <Form>
            <FormGroup row>

                Start Date

              <Col sm={2}>
                <Input
                  type="date"
                  name="startDate"
                  id="startDate"
                  placeholder="startDate"
                  value={startDate}
                  onChange={handleStartDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>

                End Date

              <Col sm={2}>
                <Input
                  type="date"
                  name="endDate"
                  id="endDate"
                  value={endDate}
                  placeholder="endDate"
                  onChange={handleEndDate}
                />
              </Col>
            </FormGroup>
            <FormGroup row>

                Expense Type

              <Col sm={2}>
                <Input
                  type="select"
                  name="expenseType"
                  value={expenseType}
                  id=" expenseType"
                  onChange={handleType}
                >
                  <option>Hotel</option>
                  <option>Airfare</option>
                  <option>Rail</option>
                  <option>All</option>
                </Input>
              </Col>
            </FormGroup>
            <FormGroup check row>
              <Col sm={{ size: 10, offset: 1 }}>
                <Button onClick={showMessage}>Submit</Button>
              </Col>
            </FormGroup>
          </Form>

            {showGetAPI == "true" && (

              <GetAPI
                startDt={startDate}
                endDt={endDate}
                exptype={expenseType}
              />

          )}

        </TabPane>
      </TabContent>

  );
};

export default TabsDemo;

GETAPI- This is a class component where i need the inputs values from above functional component to invoke the API with req. params

class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      ReportEntryID: [],
      token: null,
      Url: [
        {
          Url: "",
        },
      ],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
    return
 {this.props.startdate}
;
  }
}

export default GetAPI;

Body:
your getApi component mount on first render of your parent component.
so, you have to check using componentDidUpdate in getApi component like this.

in your getApi component

componentDidUpdate = (prevProps) => {
  console.log('prevProps',prevProps);
  console.log('this props',this.props);
}

check if your getting props or not ?
hope this will help.


来源: stackexchange

问:
run java script with selenium python
I have a website to scrape, here is the website source:

```

My objective is to extract the json data. How can I do it with selenium python?
Thank you in advance

答:
Solution

Overview:

s: Get the text between the  tags first. You could easily use requests + BeautifulSoup libraries to do that. You don't necessarily need Selenium.

Extract the string where it starts with window.searchPageData['Product'] = { and endswith } inside the text (s) within pair of  as text, here is a way for you to extract your JSON data, which what I understand, is embedded in the html-source.

import re # regex library

# Define regex pattern and compile for speed
pat = r"window.searchPageData\['Product'\] = ({\s*.*\s*})\s*\n.*"
pat = re.compile(pat)

# Extract JSON Data
json_data = pat.findall(s)[0] # s = dummy data

## Output
# { SOME JSON DATA }
```

<hr>

<h2>How to use <code>requests</code> + <code>BeautifulSoup</code> libraries for this case</h2>

<p>Since, I do not have access to your data (url or html from the url), here is a scaffolding of what you need to do to get what you want. But, obviously, I could not test it. I hope this helps.</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup as bsp

## Get respose object from the target URL
url = "http://your.target.url.here" # "http://www.google.com"
r = requests.get(url=url)

## Use BeautifulSoup to get a list of Scripts
soup = bsp(r.text, 'html.parser')
scripts = soup.find_all(name='script')

## ID your script from scripts
# Now you need to find out some pattern or
# specify which script in scripts (list) has
# your intended content
# TODO.... FOR YOU

## Special Case: Pattern located in a single place only
# If your regex pattern could be found only
# in one place in the entire html page, you
# can do this alternatively.
scripts_text = '\n'.join(scripts)
# Extract JSON Data
json_data = pat.findall(scripts_text)[0]
</code>```

Dummy Data

# Dummy Data
s = """

"""
```

ContentLicense: CC BY-SA 4.0

Title: run java script with selenium python

Body:
I have a website to scrape, here is the website source:

My objective is to extract the json data. How can I do it with selenium python?
Thank you in advance

Body:
Solution

Overview:

s: Get the text between the <script></script> tags first. You could easily use requests + BeautifulSoup libraries to do that. You don't necessarily need Selenium.

Extract the string where it starts with window.searchPageData['Product'] = { and endswith } inside the text (s) within pair of <script> tags. We will use regex (regular expression) library for that.

Assuming you already have the access to the content from the website and hence you can also extract the content from a certain tag <script></script> as text, here is a way for you to extract your JSON data, which what I understand, is embedded in the html-source.

import re # regex library

# Define regex pattern and compile for speed
pat = r"window.searchPageData\['Product'\] = ({\s*.*\s*})\s*\n.*"
pat = re.compile(pat)

# Extract JSON Data
json_data = pat.findall(s)[0] # s = dummy data

## Output
# { SOME JSON DATA }

How to use requests + BeautifulSoup libraries for this case

Since, I do not have access to your data (url or html from the url), here is a scaffolding of what you need to do to get what you want. But, obviously, I could not test it. I hope this helps.

import requests
from bs4 import BeautifulSoup as bsp

## Get respose object from the target URL
url = "http://your.target.url.here" # "http://www.google.com"
r = requests.get(url=url)

## Use BeautifulSoup to get a list of Scripts
soup = bsp(r.text, 'html.parser')
scripts = soup.find_all(name='script')

## ID your script from scripts
# Now you need to find out some pattern or
# specify which script in scripts (list) has
# your intended content
# TODO.... FOR YOU

## Special Case: Pattern located in a single place only
# If your regex pattern could be found only
# in one place in the entire html page, you
# can do this alternatively.
scripts_text = '\n'.join(scripts)
# Extract JSON Data
json_data = pat.findall(scripts_text)[0]

Dummy Data

# Dummy Data
s = """
<script>
    window.searchPageData = window.searchPageData || {};
    window.searchPageData['Product'] = { SOME JSON DATA }
    };
</script>
"""


问:
Need help retrieving Deep values from Hashtable in Powershell
I kinda need help retrieving deep values from HashTable.

My Situation: I wrote a C# executable which gives me data in JSON format that I stored in a variable $Result.
I'm able to fetch and process all fields of $Result except nested HashTable called Properties and its keys (Locations). I just need to list the cities which are mentioned in the HashTable called Properties

At the minute I'm able to get the Locations Key as shown below

PS C:\WINDOWS\system32> $Result.Properties.Locations
City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009

PS C:\WINDOWS\system32> ```
</div>
</div>
</p>

<p><strong>Expected Output</strong>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>NewYork
Seattle
Miami
SanJose</code>```

Properties Hashtable

[Properties]@
{
    accountExpires=Never;
    AccountLockedOut=False;
    mail=JamesBond@internationalspy.com;
    cn=Tom Cruise;
    codePage=0;
    countryCode=0;
    displayName=Tom Cruise;
    employeeID=743355;
    Enabled=True;
    givenName=Tom;
    instanceType=4;
    lastLogoff=12/31/1600 4:00:00 PM;
    lastLogon=3/27/2020 7:52:36 AM;
    lastLogonTimestamp=5/25/2020 12:47:07 PM;
    lockoutTime=12/31/1600 4:00:00 PM;
    logonCount=4;
    mail=jamesbond@InternalActor.com;
    Locations=City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009
}```

I need to get the fetch the list of cities which are nested with the above Hashtable.
I just want the list of cities so that I can further apply my business logic and proceed further.

答:
As the Data is no json Data you will not be able to use the internal powerhsell json cmdlets to manipulate the data. As im not aware of any internal powershell object that can handle your structure out of the box I do recommend to extract the data via .net regex:

```<code>$psString = '[Properties]@
{
    accountExpires=Never;
    AccountLockedOut=False;
    mail=JamesBond@internationalspy.com;
    cn=Tom Cruise;
    codePage=0;
    countryCode=0;
    displayName=Tom Cruise;
    employeeID=743355;
    Enabled=True;
    givenName=Tom;
    instanceType=4;
    lastLogoff=12/31/1600 4:00:00 PM;
    lastLogon=3/27/2020 7:52:36 AM;
    lastLogonTimestamp=5/25/2020 12:47:07 PM;
    lockoutTime=12/31/1600 4:00:00 PM;
    logonCount=4;
    mail=jamesbond@InternalActor.com;
    Locations=City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009
}
'
$extract = [regex]::Match($psString, 'Locations=(.*)').Groups[1].Value
$extract = [regex]::Matches($extract, 'City=([^,]*)')
$extract | foreach {echo $_.Groups[1].Value}

</code>```

gives the desired output.

Body:
I kinda need help retrieving deep values from HashTable.

My Situation: I wrote a C# executable which gives me data in JSON format that I stored in a variable $Result.
I'm able to fetch and process all fields of $Result except nested HashTable called Properties and its keys (Locations). I just need to list the cities which are mentioned in the HashTable called Properties

At the minute I'm able to get the Locations Key as shown below

PS C:\WINDOWS\system32> $Result.Properties.Locations
City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009

PS C:\WINDOWS\system32>

Expected Output:

NewYork
Seattle
Miami
SanJose

Properties Hashtable

[Properties]@
{
    accountExpires=Never;
    AccountLockedOut=False;
    mail=JamesBond@internationalspy.com;
    cn=Tom Cruise;
    codePage=0;
    countryCode=0;
    displayName=Tom Cruise;
    employeeID=743355;
    Enabled=True;
    givenName=Tom;
    instanceType=4;
    lastLogoff=12/31/1600 4:00:00 PM;
    lastLogon=3/27/2020 7:52:36 AM;
    lastLogonTimestamp=5/25/2020 12:47:07 PM;
    lockoutTime=12/31/1600 4:00:00 PM;
    logonCount=4;
    mail=jamesbond@InternalActor.com;
    Locations=City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009
}

I need to get the fetch the list of cities which are nested with the above Hashtable.
I just want the list of cities so that I can further apply my business logic and proceed further.

Body:
As the Data is no json Data you will not be able to use the internal powerhsell json cmdlets to manipulate the data. As im not aware of any internal powershell object that can handle your structure out of the box I do recommend to extract the data via .net regex:

$psString = '[Properties]@
{
    accountExpires=Never;
    AccountLockedOut=False;
    mail=JamesBond@internationalspy.com;
    cn=Tom Cruise;
    codePage=0;
    countryCode=0;
    displayName=Tom Cruise;
    employeeID=743355;
    Enabled=True;
    givenName=Tom;
    instanceType=4;
    lastLogoff=12/31/1600 4:00:00 PM;
    lastLogon=3/27/2020 7:52:36 AM;
    lastLogonTimestamp=5/25/2020 12:47:07 PM;
    lockoutTime=12/31/1600 4:00:00 PM;
    logonCount=4;
    mail=jamesbond@InternalActor.com;
    Locations=City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009
}
'
$extract = [regex]::Match($psString, 'Locations=(.*)').Groups[1].Value
$extract = [regex]::Matches($extract, 'City=([^,]*)')
$extract | foreach {echo $_.Groups[1].Value}

gives the desired output.


问:
Call a WebService and a REST API using JDK8 Streams and CompletableFuture
I have a SOAP call that I need to make and then process the results from the SOAP call in a REST call.  Each set of calls is based on a batch of records.  I am getting completely lost in trying to get this to run using JDK8 streams as asynchronous as possible.  How can I accomplish this?

SOAP Call:

```<code>CompletableFuture<Stream<Product>> getProducts(final Set<String> criteria)
{
    return supplyAsync(() -> {
        ...
        return service.findProducts(request);
    }, EXECUTOR_THREAD_POOL);
}
</code>```

REST Call:

```<code>final CompletableFuture<Stream<Result>> validateProducts(final Stream<Product> products)
{
    return supplyAsync(() -> service
        .submitProducts(products, false)
        .stream(), EXECUTOR_THREAD_POOL);
}
</code>```

I am trying to invoke the SOAP call, pass the result into the REST call, and collect the results using a JDK8 stream.  Each SOAP->REST call is a "set" of records (or batch) similar to paging.  (this is totally not working right now but just an example).

```<code>@Test
public void should_execute_validations()
{
    final Set<String> samples = generateSamples();

    //Prepare paging...
    final int total = samples.size();
    final int pages = getPages(total);
    log.debug("Items: {} / Pages: {}", total, pages);

    final Stopwatch stopwatch = createStarted();
    final Set<Result> results = range(0, pages)
        .mapToObj(index -> {
            final Set<String> subset = subset(index, samples);
            return getProducts(subset)
                .thenApply(this::validateProducts);
        })
        .flatMap(CompletableFuture::join)
        .collect(toSet());
    log.debug("Executed {} calls in {}", pages, stopwatch.stop());
    assertThat(results, notNullValue());
}
</code>```

答:
I think there are two usage that are incorrect in your example: thenApply and join.

To chain the 1st call (SOAP) and the 2nd call (REST), you need to use thenCompose instead of thenApply. This is because method "validateProducts" returns completable futures, using "thenApply" will create CompletableFuture<CompletableFuture<Stream<Result>>> in your stream mapping. But what you need is probably CompletableFuture<Stream<Result>>. Using thenCompose can resolve this problem, because it is analogous to "Optional.flatMap" or "Stream.flatMap":

```<code>.mapToObj(index -> {
    final Set<String> subset = subset(index, samples);
    return getProducts(subset)
        .thenCompose(this::validateProducts);
})
</code>```

The 2nd incorrect usage is join. Using join blocks the current thread waiting for the result of that CompletableFuture. In your cases, there are N completable futures, where N is the number of pages. Instead of waiting them one by one, the better solution is to wait all the them use CompletableFuture.allOf(...). This method returns a new CompletableFuture that is completed when all of the given CompletableFutures complete. So I suggest that you modify your stream usage and return a list of futures. Then, wait the completion. And finally, retrieve the results:

```<code>List<CompletableFuture<Stream<Result>>> futures = range(0, pages)
    .mapToObj(index -> {
        final Set<String> subset = subset(index, samples);
        return getProducts(subset).thenCompose(this::validateProducts);
    })
    .collect(Collectors.toList());

CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

for (CompletableFuture<Stream<Result>> cf : futures) {
  // TODO Handle the results and exceptions here
}
</code>```

You can see the complete program on GitHub.

Body:
I have a SOAP call that I need to make and then process the results from the SOAP call in a REST call.  Each set of calls is based on a batch of records.  I am getting completely lost in trying to get this to run using JDK8 streams as asynchronous as possible.  How can I accomplish this?

SOAP Call:

CompletableFuture<Stream<Product>> getProducts(final Set<String> criteria)
{
    return supplyAsync(() -> {
        ...
        return service.findProducts(request);
    }, EXECUTOR_THREAD_POOL);
}

REST Call:

final CompletableFuture<Stream<Result>> validateProducts(final Stream<Product> products)
{
    return supplyAsync(() -> service
        .submitProducts(products, false)
        .stream(), EXECUTOR_THREAD_POOL);
}

I am trying to invoke the SOAP call, pass the result into the REST call, and collect the results using a JDK8 stream.  Each SOAP->REST call is a "set" of records (or batch) similar to paging.  (this is totally not working right now but just an example).

@Test
public void should_execute_validations()
{
    final Set<String> samples = generateSamples();

    //Prepare paging...
    final int total = samples.size();
    final int pages = getPages(total);
    log.debug("Items: {} / Pages: {}", total, pages);

    final Stopwatch stopwatch = createStarted();
    final Set<Result> results = range(0, pages)
        .mapToObj(index -> {
            final Set<String> subset = subset(index, samples);
            return getProducts(subset)
                .thenApply(this::validateProducts);
        })
        .flatMap(CompletableFuture::join)
        .collect(toSet());
    log.debug("Executed {} calls in {}", pages, stopwatch.stop());
    assertThat(results, notNullValue());
}

Body:
I think there are two usage that are incorrect in your example: thenApply and join.

To chain the 1st call (SOAP) and the 2nd call (REST), you need to use thenCompose instead of thenApply. This is because method "validateProducts" returns completable futures, using "thenApply" will create CompletableFuture<CompletableFuture<Stream<Result>>> in your stream mapping. But what you need is probably CompletableFuture<Stream<Result>>. Using thenCompose can resolve this problem, because it is analogous to "Optional.flatMap" or "Stream.flatMap":

.mapToObj(index -> {
    final Set<String> subset = subset(index, samples);
    return getProducts(subset)
        .thenCompose(this::validateProducts);
})

The 2nd incorrect usage is join. Using join blocks the current thread waiting for the result of that CompletableFuture. In your cases, there are N completable futures, where N is the number of pages. Instead of waiting them one by one, the better solution is to wait all the them use CompletableFuture.allOf(...). This method returns a new CompletableFuture that is completed when all of the given CompletableFutures complete. So I suggest that you modify your stream usage and return a list of futures. Then, wait the completion. And finally, retrieve the results:

List<CompletableFuture<Stream<Result>>> futures = range(0, pages)
    .mapToObj(index -> {
        final Set<String> subset = subset(index, samples);
        return getProducts(subset).thenCompose(this::validateProducts);
    })
    .collect(Collectors.toList());

CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

for (CompletableFuture<Stream<Result>> cf : futures) {
  // TODO Handle the results and exceptions here
}

You can see the complete program on GitHub.


问:
CSS not affecting bootstrap navbar background color
I'm trying to set a new color for a bootstrap navbar component but having trouble. Does it have to do with failure to override bootstrap or css link placement? I've tried omitting the bootstrap bg-light setting and defining the navbar background color in main.css as well. What am I missing? Here is the HTML of interest:

```<code>{% extends 'bootstrap/base.html' %}

{% block title %}Welcome{% endblock title %}

{% block html_attribs %}lang='en'{% endblock html_attribs %}

{% block head %}
<head>
    <!-- Required meta tags -->
    {% block meta %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    {% endblock meta %}

    <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type='text/css' href="{{ url_for('static', filename='main.css' )}}">

    <title>Welcome</title>

    {% block navbar %}
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
          <div class="navbar-nav">
            <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
            <a class="nav-item nav-link" href="#">About</a>
            <a class="nav-item nav-link" href="#">Register</a>
            <a class="nav-item nav-link disabled" href="#">Login</a>
          </div>
        </div>
      </nav>
    {% endblock navbar %}
  </head>
{% endblock head %}

{% block body %}
<body>
    <h1></h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
{% endblock body %}

{% block scripts %}
{{ super() }}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
{% endblock scripts %}
</code>```

And here is the "main.css" file:

```<code>body {
    background: #F9DCC4;
    color: #333333;
  }

  .navbar-expand-lg {
    background-color: rgb(150, 144, 143);
  }
</code>```

Thanks!

答:
You can remove the bg-light class from the navbar and in css you can write --></p>

```<code>nav {
    background-color: rgb(150, 144, 143);
   {
</code>```

Body:
I'm trying to set a new color for a bootstrap navbar component but having trouble. Does it have to do with failure to override bootstrap or css link placement? I've tried omitting the bootstrap bg-light setting and defining the navbar background color in main.css as well. What am I missing? Here is the HTML of interest:

{% extends 'bootstrap/base.html' %}

{% block title %}Welcome{% endblock title %}

{% block html_attribs %}lang='en'{% endblock html_attribs %}

{% block head %}

    {% block meta %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    {% endblock meta %}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type='text/css' href="{{ url_for('static', filename='main.css' )}}">

    <title>Welcome</title>

    {% block navbar %}

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

        </button>

            Home (current)
            About
            Register
            Login

    {% endblock navbar %}

{% endblock head %}

{% block body %}

{% endblock body %}

{% block scripts %}
{{ super() }}

{% endblock scripts %}

And here is the "main.css" file:

body {
    background: #F9DCC4;
    color: #333333;
  }

  .navbar-expand-lg {
    background-color: rgb(150, 144, 143);
  }

Thanks!

Body:
You can remove the bg-light class from the navbar and in css you can write -->

nav {
    background-color: rgb(150, 144, 143);
   {


问:
Better way of writing a long and simple if statement?
I am writing some custom values for a variable.
Is there a better way of writing this?</p>

```<code>if val == 1:
    val = -20
elif val == 2:
    val = -15
elif val == 3:
    val = -10
elif val == 4:
    val = -5
elif val == 5:
    val = 0
elif val == 6:
    val = 4
elif val == 7:
    val = 8
elif val == 8:
    val = 12
elif val == 9:
    val = 16
elif val == 10:
    val = 20
</code>```

Body:
I am writing some custom values for a variable.
Is there a better way of writing this?

if val == 1:
    val = -20
elif val == 2:
    val = -15
elif val == 3:
    val = -10
elif val == 4:
    val = -5
elif val == 5:
    val = 0
elif val == 6:
    val = 4
elif val == 7:
    val = 8
elif val == 8:
    val = 12
elif val == 9:
    val = 16
elif val == 10:
    val = 20

Body:
Thanks to Michael Butscher for the idea:

    values = {
        1: -20,
        2: -15,
        3: -10,
        4: -5,
        5: 0,
        6: 4,
        7: 8,
        8: 12,
        9: 16,
        10: 20,
    }

    value = values.get(value)


问:
applying stats.linregress to every grid cell in a netcdf file
i have a netcdf file containing the following:

<xarray.Dataset>
Dimensions:    (latitude: 65, longitude: 49, time: 7306)
Coordinates:
  * latitude   (latitude) float32 21.0 20.75 20.5 20.25 ... 5.75 5.5 5.25 5.0
  * longitude  (longitude) float32 116.0 116.25 116.5 ... 127.5 127.75 128.0
  * time       (time) datetime64[ns] 1985-12-31T23:00:00 ... 2005-12-31T11:00:00
Data variables:
    pr         (time, latitude, longitude) float32 0.049636062 ... 0.6215298
    time_bnds  (time) datetime64[ns] 1985-12-31T23:00:00 ... 2005-12-31T11:00:00

my goal is to apply stats.linregress to every grid cell of this data set
and i took the following approach:

```<code>from scipy import stats
import nump as np
import xarray as xr

#load data
rain = xr.load_dataset('../precipitation.1986-2005.nc')

#group by (lon,lat) pairs by:
stacked = rain.stack(paired_points=['latitude','longitude'])
grouped = stacked.groupby('paired_points').apply(stats.linregress(stacked.time.astype(float),stacked['pr']))
unstack = grouped.unstack('paired_points')
</code>```

after application of stats.linregress i want to create a plot where every grid cell is colored by the value of the slope calculated from the linear regression.

when i run the code a ValueError is raised:

```<code>ValueError: all the input array dimensions for the concatenation
axis must match exactly, but along dimension 1, the array at index 0 has size 7306 and the
array at index 1 has size 3185
</code>```

it seems as if accessing the per-grid precipitation time series and successfully applying stats.linregress for each grid cell is where the problem is.

could someone suggest a way forward?

your help would be valued.

答:
This has been resolved via:

```<code>rain = xr.load_dataset('../precipitation.1986-2005.nc')

def slope(x):
sl = stats.linregress(x.time.astype(float),x[dict(paired_points=0)]).slope
return xr.DataArray(sl)
</code>```

#group by (lon,lat) pairs by:
stacked = rain.stack(paired_points=['latitude','longitude'])
grouped=stacked.groupby('paired_points').apply(slope)
unstack = grouped.unstack('paired_points')

the solution above follows the
approach taken by Dr. Ryan Abernathey in

https://gist.github.com/rabernat/bc4c6990eb20942246ce967e6c9c3dbe

Body:
i have a netcdf file containing the following:

<xarray.Dataset>
Dimensions:    (latitude: 65, longitude: 49, time: 7306)
Coordinates:
  * latitude   (latitude) float32 21.0 20.75 20.5 20.25 ... 5.75 5.5 5.25 5.0
  * longitude  (longitude) float32 116.0 116.25 116.5 ... 127.5 127.75 128.0
  * time       (time) datetime64[ns] 1985-12-31T23:00:00 ... 2005-12-31T11:00:00
Data variables:
    pr         (time, latitude, longitude) float32 0.049636062 ... 0.6215298
    time_bnds  (time) datetime64[ns] 1985-12-31T23:00:00 ... 2005-12-31T11:00:00

my goal is to apply stats.linregress to every grid cell of this data set
and i took the following approach:

from scipy import stats
import nump as np
import xarray as xr

#load data
rain = xr.load_dataset('../precipitation.1986-2005.nc')

#group by (lon,lat) pairs by:
stacked = rain.stack(paired_points=['latitude','longitude'])
grouped = stacked.groupby('paired_points').apply(stats.linregress(stacked.time.astype(float),stacked['pr']))
unstack = grouped.unstack('paired_points')

after application of stats.linregress i want to create a plot where every grid cell is colored by the value of the slope calculated from the linear regression.

when i run the code a ValueError is raised:

ValueError: all the input array dimensions for the concatenation
axis must match exactly, but along dimension 1, the array at index 0 has size 7306 and the
array at index 1 has size 3185

it seems as if accessing the per-grid precipitation time series and successfully applying stats.linregress for each grid cell is where the problem is.

could someone suggest a way forward?

your help would be valued.

Body:
This has been resolved via:

rain = xr.load_dataset('../precipitation.1986-2005.nc')

def slope(x):
sl = stats.linregress(x.time.astype(float),x[dict(paired_points=0)]).slope
return xr.DataArray(sl)

#group by (lon,lat) pairs by:
stacked = rain.stack(paired_points=['latitude','longitude'])
grouped=stacked.groupby('paired_points').apply(slope)
unstack = grouped.unstack('paired_points')

the solution above follows the
approach taken by Dr. Ryan Abernathey in

https://gist.github.com/rabernat/bc4c6990eb20942246ce967e6c9c3dbe


问:
Tagging One Record with Another in Rails
I am attempting to create a model where an user can attach a record to an associated record through tagging in rails. I have this mostly functional however when I attempt to add a tag to an active record the tag is only added to the secondary record. For example, if I was trying to tag Record 2 to Record 1, it would instead tag Record 2 to Record 2. My current code is below:

RecordTagging Model

```<code>class Recordtagging < ApplicationRecord
  belongs_to :record
end
</code>```

Record Controller

```<code>def record_params
        params.require(:record).permit(:name, :record_list, :record, { record_ids: [] }, :record_ids)
    end
</code>```

Record Model

```<code>class Record < ApplicationRecord

    has_many :Recordtaggings
    has_many :records, through: :recordtaggings

    validates :name, presence: true
    validates :name, uniqueness: true

    def self.recordtagged_with(name)
        Record.find_by!(name: name).records
    end

    def self.record_counts
        Record.select('records.*, count(recordtaggings.record_id) as count').joins(:recordtaggings).group('recordtaggings.record_id')
    end

    def record_list
        record.map(&:name).join(', ')
    end

    def record_list=(names)
        self.records = names.split(',').map do |n|
            Record.where(name: n.strip).first_or_create!
        end
    end
end
</code>```

Record Show

```<code><%= raw @record.records.map(&:name).map { |t| link_to t, records_path(t) }.join(', ') %>
</code>```

答:
To maintain a relation between Record object to another Record object, the middle man RecordTagging must have two fields specifying first record and second record. Here you have specified only one field record_id on RecordTagging, which tags a record to itself.

what you need is

```<code>class RecordTagging
   belongs_to record_1, class_name: 'Record', optional: true
   belongs_to record_2, class_name: 'Record', optional: true
end
</code>```

Body:
I am attempting to create a model where an user can attach a record to an associated record through tagging in rails. I have this mostly functional however when I attempt to add a tag to an active record the tag is only added to the secondary record. For example, if I was trying to tag Record 2 to Record 1, it would instead tag Record 2 to Record 2. My current code is below:

RecordTagging Model

class Recordtagging < ApplicationRecord
  belongs_to :record
end

Record Controller

def record_params
        params.require(:record).permit(:name, :record_list, :record, { record_ids: [] }, :record_ids)
    end

Record Model

class Record < ApplicationRecord

    has_many :Recordtaggings
    has_many :records, through: :recordtaggings

    validates :name, presence: true
    validates :name, uniqueness: true

    def self.recordtagged_with(name)
        Record.find_by!(name: name).records
    end

    def self.record_counts
        Record.select('records.*, count(recordtaggings.record_id) as count').joins(:recordtaggings).group('recordtaggings.record_id')
    end

    def record_list
        record.map(&:name).join(', ')
    end

    def record_list=(names)
        self.records = names.split(',').map do |n|
            Record.where(name: n.strip).first_or_create!
        end
    end
end

Record Show

<%= raw @record.records.map(&:name).map { |t| link_to t, records_path(t) }.join(', ') %>

Body:
To maintain a relation between Record object to another Record object, the middle man RecordTagging must have two fields specifying first record and second record. Here you have specified only one field record_id on RecordTagging, which tags a record to itself.

what you need is

class RecordTagging
   belongs_to record_1, class_name: 'Record', optional: true
   belongs_to record_2, class_name: 'Record', optional: true
end


问:
Effective use of a DLL
Up until now I've only used DLL's as a source for plugins in my applications.

But I know that using DLL's will allow me to update my program "client side" a lot easier the re-downloading the main EXE all time.

The problem is, I cant seem to find an effective way to use dll's in my application, or to use them in a way that would impact the program, but not force me to change the way the entire program works.

The "application" in this instance is an XNA Game.

So for example, I have three main classes (excluding the main game Class)

Units
Players
Networking.

I would like to have the Units/Players in one DLL, and the Networking in another DLL, or at least move the networking to a separate DLL, But the way the networking class works and is coded would require the DLL to have a reference to the Game, and the Game to have a reference to the DLL, which is prevented in Visual Studio to prevent circular dependencies.

My question, is how can I effectively use a DLL to store my networking class, I have a couple of ideas, but I'm not sure how feasible any of them is yet.

What I would like, if possible, would be to have the entire networking instance running from the dll, sending receiving, and updating the game data as needed.

But so far I have only been able to come up with a way to have the receiving and sending in the Main game.exe and move the handling functions into the dll, and even then, the handling functions cannot (easily) communicate with the game.

I also thought of using the Plugin System, but that requires me to use Delegates for all my functions that I want to use in the Networking DLL, and seems very inefficient in the long run.

If this sort of thing cant be done with DLL's (back and forth communication between the Host program and dll), then what use are they anyway?

Sure I can have simple functions, like my "Color" class, to parse and return color codes, but simple things aren't going to change, and need to be updated.

Anyway, I always tend to ramble about things that don't matter (for the most part), so thanks for taking a look, and for any responses :)

答:
OK - so you have 3 classes with dependencies on each other.

Can you change the relationship so that instead of one class referencing another, instead you reference an interface?

E.g. ClassA has a method which uses ClassB - MethodB1
ClassB implements interface IB, so now Class A has instead a reference to IB

Put all your interfaces in a separate assembly.
Now A, B and C have no reference to each other - just to the interface class.
In your executable use Dependency Injection to wire up the Concrete class implementations.

ContentLicense: CC BY-SA 3.0

Title: Effective use of a DLL


问:
SQL: get the latest record in each day of each user
I have a table that looks like

```<code>user_id behavior time
A B1 2020-05-30 09:07:21
A B1 2020-05-31 12:38:21
A B2 2020-05-31 14:39:23
B B1 2020-05-31 12:32:09
</code>```

I would like to get the latest records in each day of each user, so the above table will become

```<code>    user_id behavior time
    A B1 2020-05-30 09:07:21
    A B2 2020-05-31 14:39:23
    B B1 2020-05-31 12:32:09
</code>```

I look to some other questions in stackoverflow but did not find exactly what I am looking for.

Thanks for your help.

答:
You can try with row_number(), you have to partition by user_id, behavior and date.

```<code>select
    user_id,
    behavior,
    time
from
(
    select
        *,
        row_number() over (partition by user_id, behavior, to_date(time) order by time desc) as rnk
    from yourTable
) val
where rnk = 1
</code>```

Output:

```<code>| user_id | behavior | time                     |
| ------- | -------- | ------------------------ |
| A       | B1       | 2020-05-30 09:07:21      |
| A       | B2       | 2020-05-31 14:39:23      |
| B       | B1       | 2020-05-31 12:32:09      |
</code>```

Body:
I have a table that looks like

user_id behavior time
A B1 2020-05-30 09:07:21
A B1 2020-05-31 12:38:21
A B2 2020-05-31 14:39:23
B B1 2020-05-31 12:32:09

I would like to get the latest records in each day of each user, so the above table will become

    user_id behavior time
    A B1 2020-05-30 09:07:21
    A B2 2020-05-31 14:39:23
    B B1 2020-05-31 12:32:09

I look to some other questions in stackoverflow but did not find exactly what I am looking for.

Thanks for your help.

Body:
You can try with row_number(), you have to partition by user_id, behavior and date.

select
    user_id,
    behavior,
    time
from
(
    select
        *,
        row_number() over (partition by user_id, behavior, to_date(time) order by time desc) as rnk
    from yourTable
) val
where rnk = 1

Output:

| user_id | behavior | time                     |
| ------- | -------- | ------------------------ |
| A       | B1       | 2020-05-30 09:07:21      |
| A       | B2       | 2020-05-31 14:39:23      |
| B       | B1       | 2020-05-31 12:32:09      |


问:
Can we interact with Google Devtools Application element from R?
I would like t download the cookies details highlighted in the attached screen and save it the an R data frame. Is there a way to do it? Any help would be much appreciated!

enter image description here

答:
This only gets you one cookie that is listed in you image, not sure how to get all of them:</p>

```<code>library(rvest)
url1 <- "enter_desired_url" #enter url you want to scrape
my_session <- html_session(url1)

library(httr)
cookie <- cookies(my_session) #cookies are saved in a table
cookie
</code>```

Body:
This only gets you one cookie that is listed in you image, not sure how to get all of them:

library(rvest)
url1 <- "enter_desired_url" #enter url you want to scrape
my_session <- html_session(url1)

library(httr)
cookie <- cookies(my_session) #cookies are saved in a table
cookie


问:
Is there a program that allows you to write "pretty" library tutorials?
I need to write tutorial for a library I wrote. The tutorial should also include code.
I wonder if there is a platform/application that provides a nice option for writing such tutorials with code?</p>

答: Sandcastle might help (it generates documentation files from XML code comments (assuming whatever language your library is written in supports this)). Though I'd describe the output as functional rather than pretty.</p>


问:
edit static files (index.html) from yarn build
I used yarn build to create static files for my react app. Now, I want to edit the index.html file in ./build but whenever I add something it gives me an error Uncaught SyntaxError: Unexpected token '<'. Is there a correct way to edit that file?

答:
In your react project you will see a folder called public. Include your hello.js file in that folder. You will also find an index.html file. Include your script tag as follows.

```<code><script src="%PUBLIC_URL%/hello.js" />
</code>```

Body:
In your react project you will see a folder called public. Include your hello.js file in that folder. You will also find an index.html file. Include your script tag as follows.

<script src="%PUBLIC_URL%/hello.js" />


问:
Walking the NTFS Change Journal on Windows 10
I'm trying to read the NTFS Change Journal but I've noticed that all the example code I can find fails on Windows 10, even though it works on Windows 7.

For example, Microsofts own example Walking a Buffer of Change Journal Records works on Windows 7 but when I run the same code on Windows 10 I get an error 87 (The parameter is incorrect) when I call DeviceIoControl with FSCTL_READ_USN_JOURNAL (Note that the earlier call to DeviceIoControl with FSCTL_QUERY_USN_JOURNAL completes successfully and return valid data.).

I've even taken the EXE compiled and working on Windows 7 and copied it to the Windows 10 machine and it still fails, so I believe that Windows 10 may be more strict on parameter validation or something like that?

I am running the code as Administrator, so that's not the issue.

I can't find any other references to this problem, but I get the same issue if I take other peoples example code and attempt to run it on Windows 10.

Edit:

The code itself:

```<code>#include <Windows.h>
#include <WinIoCtl.h>
#include <stdio.h>

#define BUF_LEN 4096

void main()
{
   HANDLE hVol;
   CHAR Buffer[BUF_LEN];

   USN_JOURNAL_DATA JournalData;
   READ_USN_JOURNAL_DATA ReadData = {0, 0xFFFFFFFF, FALSE, 0, 0};
   PUSN_RECORD UsnRecord;

   DWORD dwBytes;
   DWORD dwRetBytes;
   int I;

   hVol = CreateFile( TEXT("\\\\.\\c:"),
               GENERIC_READ | GENERIC_WRITE,
               FILE_SHARE_READ | FILE_SHARE_WRITE,
               NULL,
               OPEN_EXISTING,
               0,
               NULL);

   if( hVol == INVALID_HANDLE_VALUE )
   {
      printf("CreateFile failed (%d)\n", GetLastError());
      return;
   }

   if( !DeviceIoControl( hVol,
          FSCTL_QUERY_USN_JOURNAL,
          NULL,
          0,
          &JournalData,
          sizeof(JournalData),
          &dwBytes,
          NULL) )
   {
      printf( "Query journal failed (%d)\n", GetLastError());
      return;
   }

   ReadData.UsnJournalID = JournalData.UsnJournalID;

   printf( "Journal ID: %I64x\n", JournalData.UsnJournalID );
   printf( "FirstUsn: %I64x\n\n", JournalData.FirstUsn );

   for(I=0; I<=10; I++)
   {
      memset( Buffer, 0, BUF_LEN );

      if( !DeviceIoControl( hVol,
            FSCTL_READ_USN_JOURNAL,
            &ReadData,
            sizeof(ReadData),
            &Buffer,
            BUF_LEN,
            &dwBytes,
            NULL) )
      {
         printf( "Read journal failed (%d)\n", GetLastError());
         return;
      }

      dwRetBytes = dwBytes - sizeof(USN);

      // Find the first record
      UsnRecord = (PUSN_RECORD)(((PUCHAR)Buffer) + sizeof(USN));

      printf( "****************************************\n");

      // This loop could go on for a long time, given the current buffer size.
      while( dwRetBytes > 0 )
      {
         printf( "USN: %I64x\n", UsnRecord->Usn );
         printf("File name: %.*S\n",
                  UsnRecord->FileNameLength/2,
                  UsnRecord->FileName );
         printf( "Reason: %x\n", UsnRecord->Reason );
         printf( "\n" );

         dwRetBytes -= UsnRecord->RecordLength;

         // Find the next record
         UsnRecord = (PUSN_RECORD)(((PCHAR)UsnRecord) +
                  UsnRecord->RecordLength);
      }
      // Update starting USN for next call
      ReadData.StartUsn = *(USN *)&Buffer;
   }

   CloseHandle(hVol);
}
</code>```

答:
Replace the READ_USN_JOURNAL_DATA structure with READ_USN_JOURNAL_DATA_V0 data structure and initialize it.

This worked for me

```<code>READ_USN_JOURNAL_DATA_V0 ReadData;
ZeroMemory(&ReadData, sizeof(ReadData));
ReadData.ReasonMask = 0xFFFFFFFF;
</code>```

Body:
I'm trying to read the NTFS Change Journal but I've noticed that all the example code I can find fails on Windows 10, even though it works on Windows 7.

For example, Microsofts own example Walking a Buffer of Change Journal Records works on Windows 7 but when I run the same code on Windows 10 I get an error 87 (The parameter is incorrect) when I call DeviceIoControl with FSCTL_READ_USN_JOURNAL (Note that the earlier call to DeviceIoControl with FSCTL_QUERY_USN_JOURNAL completes successfully and return valid data.).

I've even taken the EXE compiled and working on Windows 7 and copied it to the Windows 10 machine and it still fails, so I believe that Windows 10 may be more strict on parameter validation or something like that?

I am running the code as Administrator, so that's not the issue.

I can't find any other references to this problem, but I get the same issue if I take other peoples example code and attempt to run it on Windows 10.

Edit:

The code itself:

#include <Windows.h>
#include <WinIoCtl.h>
#include <stdio.h>

#define BUF_LEN 4096

void main()
{
   HANDLE hVol;
   CHAR Buffer[BUF_LEN];

   USN_JOURNAL_DATA JournalData;
   READ_USN_JOURNAL_DATA ReadData = {0, 0xFFFFFFFF, FALSE, 0, 0};
   PUSN_RECORD UsnRecord;

   DWORD dwBytes;
   DWORD dwRetBytes;
   int I;

   hVol = CreateFile( TEXT("\\\\.\\c:"),
               GENERIC_READ | GENERIC_WRITE,
               FILE_SHARE_READ | FILE_SHARE_WRITE,
               NULL,
               OPEN_EXISTING,
               0,
               NULL);

   if( hVol == INVALID_HANDLE_VALUE )
   {
      printf("CreateFile failed (%d)\n", GetLastError());
      return;
   }

   if( !DeviceIoControl( hVol,
          FSCTL_QUERY_USN_JOURNAL,
          NULL,
          0,
          &JournalData,
          sizeof(JournalData),
          &dwBytes,
          NULL) )
   {
      printf( "Query journal failed (%d)\n", GetLastError());
      return;
   }

   ReadData.UsnJournalID = JournalData.UsnJournalID;

   printf( "Journal ID: %I64x\n", JournalData.UsnJournalID );
   printf( "FirstUsn: %I64x\n\n", JournalData.FirstUsn );

   for(I=0; I<=10; I++)
   {
      memset( Buffer, 0, BUF_LEN );

      if( !DeviceIoControl( hVol,
            FSCTL_READ_USN_JOURNAL,
            &ReadData,
            sizeof(ReadData),
            &Buffer,
            BUF_LEN,
            &dwBytes,
            NULL) )
      {
         printf( "Read journal failed (%d)\n", GetLastError());
         return;
      }

      dwRetBytes = dwBytes - sizeof(USN);

      // Find the first record
      UsnRecord = (PUSN_RECORD)(((PUCHAR)Buffer) + sizeof(USN));

      printf( "****************************************\n");

      // This loop could go on for a long time, given the current buffer size.
      while( dwRetBytes > 0 )
      {
         printf( "USN: %I64x\n", UsnRecord->Usn );
         printf("File name: %.*S\n",
                  UsnRecord->FileNameLength/2,
                  UsnRecord->FileName );
         printf( "Reason: %x\n", UsnRecord->Reason );
         printf( "\n" );

         dwRetBytes -= UsnRecord->RecordLength;

         // Find the next record
         UsnRecord = (PUSN_RECORD)(((PCHAR)UsnRecord) +
                  UsnRecord->RecordLength);
      }
      // Update starting USN for next call
      ReadData.StartUsn = *(USN *)&Buffer;
   }

   CloseHandle(hVol);
}

Body:
Replace the READ_USN_JOURNAL_DATA structure with READ_USN_JOURNAL_DATA_V0 data structure and initialize it.

This worked for me

READ_USN_JOURNAL_DATA_V0 ReadData;
ZeroMemory(&ReadData, sizeof(ReadData));
ReadData.ReasonMask = 0xFFFFFFFF;


问:
How do i drag item from QListWidget and drop to QPlainTextEdit?

As shown in the image on the left side i have a QListWidget named "my_listwidget" populated with 3 commands and on the right side i have a QPlainTextEdit named "my_textedit".

i am able to drag from QListWidget by using this code

```<code>ui->block_commands_listwidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->block_commands_listwidget->setDragEnabled(true);
ui->block_commands_listwidget ->setDragDropMode(QAbstractItemView::DragDrop);
ui->block_commands_listwidget->viewport()->setAcceptDrops(false);
ui->block_commands_listwidget->setDropIndicatorShown(true);
</code>```

But i am not able to drop into my QPlainTextEdit, i guess because when i drag, its of "item type" and when im trying to drop into textbox, the QPlainTextEdit accepts only Text but not item type.
How do i do this ?
Thanks for going through this.

答:
The problem is simple: QPlaintTextEdit does not recognize the mimetype that the QListWidget sends by default, so the solution is to override the mimeData() method adding the text of the selected items as plain text:

```<code>#include <QtWidgets>

class ListWidget: public QListWidget{
public:
    using QListWidget::QListWidget;
protected:
    QMimeData *mimeData(const QList<QListWidgetItem *> items) const
    {
        QMimeData *md = QListWidget::mimeData(items);
        QStringList texts;
        for(QListWidgetItem *item : selectedItems())
            texts << item->text();
        md->setText(texts.join(QStringLiteral("\n")));
        return md;
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    ListWidget *lw = new ListWidget;
    lw->addItems({"First Command", "Second Command", "Third Command"});
    lw->setSelectionMode(QAbstractItemView::SingleSelection);
    lw->setDragEnabled(true);
    lw->setDragDropMode(QAbstractItemView::DragOnly);
    QPlainTextEdit *pe = new QPlainTextEdit;
    QHBoxLayout *lay = new QHBoxLayout(&w);
    lay->addWidget(lw);
    lay->addWidget(pe);
    w.show();
    return a.exec();
}
</code>```

Body:
As shown in the image on the left side i have a QListWidget named "my_listwidget" populated with 3 commands and on the right side i have a QPlainTextEdit named "my_textedit".

i am able to drag from QListWidget by using this code

ui->block_commands_listwidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->block_commands_listwidget->setDragEnabled(true);
ui->block_commands_listwidget ->setDragDropMode(QAbstractItemView::DragDrop);
ui->block_commands_listwidget->viewport()->setAcceptDrops(false);
ui->block_commands_listwidget->setDropIndicatorShown(true);

But i am not able to drop into my QPlainTextEdit, i guess because when i drag, its of "item type" and when im trying to drop into textbox, the QPlainTextEdit accepts only Text but not item type.
How do i do this ?
Thanks for going through this.

Body:
The problem is simple: QPlaintTextEdit does not recognize the mimetype that the QListWidget sends by default, so the solution is to override the mimeData() method adding the text of the selected items as plain text:

#include <QtWidgets>

class ListWidget: public QListWidget{
public:
    using QListWidget::QListWidget;
protected:
    QMimeData *mimeData(const QList<QListWidgetItem *> items) const
    {
        QMimeData *md = QListWidget::mimeData(items);
        QStringList texts;
        for(QListWidgetItem *item : selectedItems())
            texts << item->text();
        md->setText(texts.join(QStringLiteral("\n")));
        return md;
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    ListWidget *lw = new ListWidget;
    lw->addItems({"First Command", "Second Command", "Third Command"});
    lw->setSelectionMode(QAbstractItemView::SingleSelection);
    lw->setDragEnabled(true);
    lw->setDragDropMode(QAbstractItemView::DragOnly);
    QPlainTextEdit *pe = new QPlainTextEdit;
    QHBoxLayout *lay = new QHBoxLayout(&w);
    lay->addWidget(lw);
    lay->addWidget(pe);
    w.show();
    return a.exec();
}


问:
Flutter how to show percentage type container
I need to show this type of line in my flutter app but dont get any idea how ill build this

If have simple background line now

```<code>Container(color: Color(0xffABEBC6 ), width: width * 0.7, height: 4,),
</code>```

But i need add this thick dark shade line on that.

答:
This is one way to do it:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage()
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double totalWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(children: [
              Container(color: Colors.green[900], height: 4, width: 0.7 * totalWidth),
              Container(color: Color(0xffABEBC6), height: 4, width: 0.3 * totalWidth),

            ])
          ],
        ),
      ),
    );
  }
}
</code>```

If you want something more dynamic, check out LinearProgressIndicator

Body:
I need to show this type of line in my flutter app but dont get any idea how ill build this

If have simple background line now

Container(color: Color(0xffABEBC6 ), width: width * 0.7, height: 4,),

But i need add this thick dark shade line on that.

Body:
This is one way to do it:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage()
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double totalWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(children: [
              Container(color: Colors.green[900], height: 4, width: 0.7 * totalWidth),
              Container(color: Color(0xffABEBC6), height: 4, width: 0.3 * totalWidth),

            ])
          ],
        ),
      ),
    );
  }
}

If you want something more dynamic, check out LinearProgressIndicator


问:
Add checkbox and then click a button to record into firebase
I am currently working on a web app using firebase where a teacher can reserve rooms in a school. Here is the code so far:

app.js:

```<code>const roomList = document.querySelector('#room-list');
function renderRoom(doc){
    let li = document.createElement('li');
    let buildingNumber = document.createElement('spam');
    let floorNumber = document.createElement('span');
    let roomNumber = document.createElement('span');
    let block = document.createElement('span');
    let firstName = document.createElement('span');
    let lastName = document.createElement('span');
    li.setAttribute('data-id', doc.id);
    buildingNumber.textContent = 'Room: ' + doc.data().buildingNumber + '-' + doc.data().floorNumber + doc.data().roomNumber;
    block.textContent = 'Block: ' + doc.data().block;
    firstName.textContent = 'First Name: ' + doc.data().firstName;
    lastName.textContent = 'Last Name: ' + doc.data().lastName;
    li.appendChild(buildingNumber);
    li.appendChild(floorNumber);
    li.appendChild(roomNumber);
    li.appendChild(block);
    li.appendChild(firstName);
    li.appendChild(lastName);
    roomList.appendChild(li);
}
db.collection('rooms').where('buildingNumber', '==' , '5').where('floorNumber' , '==' , '1').onSnapshot(snapshot =>  {
    let changes = snapshot.docChanges();
    changes.forEach(change => {
        if(change.type == 'added'){
            renderRoom(change.doc);
        } else if (change.type == 'removed'){
            let li = roomList.querySelector('[data-id = ' + change.doc.id + ']');
            roomList.removeChild(li);
        }
    })
})
</code>```

app.html:

```<code><!DOCTYPE html>
<html>
    <head>
    <link rel = "stylesheet" href = "Styles.css">
    </head>
    <body>
        <h1>Select the room:</h1>
        <div class = "content">
        <form id = "add-room-list"></form>
        <ul id = "room-list"></ul>
        </div>
        <!-- The core Firebase JS SDK is always required and must be listed first -->
        <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>

        <!-- TODO: Add SDKs for Firebase products that you want to use
            https://firebase.google.com/docs/web/setup#available-libraries -->

        <script>
        // Your web app's Firebase configuration
        var firebaseConfig = {
            apiKey: "AIzaSyDNB4Ag8hXa_FDEYdWmQ2H_GMVBpWm1-0k",
            authDomain: "internal-assessment-20dd7.firebaseapp.com",
            databaseURL: "https://internal-assessment-20dd7.firebaseio.com",
            projectId: "internal-assessment-20dd7",
            storageBucket: "internal-assessment-20dd7.appspot.com",
            messagingSenderId: "905998751828",
            appId: "1:905998751828:web:1d88f0d2f655eb6141f5c1"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        const db = firebase.firestore();
        </script>
    </form>
    </body>
</html>
</code>```

This currently displays a room someone enters. I was wondering how you can add a checkbox to the left of each room so you can click on it and then click a button and it would record the selected room into firebase. Thanks.

答:
First, you need to get the values from the checkbox into Javascript variables, so you can use them in your Firestore set. Once you have done that, your code to save the values into Firestore should be something like this:

```<code>// Add a new document in the collection
db.collection("<your_collection>").doc("<your_doc>").set({
    field1: value1
    field2: value2
    ...
})
.then(function() {
    console.log("Document successfully written!");
})
.catch(function(error) {
    console.error("Error writing document: ", error);
});
</code>```

This code is untested and doesn't have your collection and documents names, but you should have it in your Javascript like this, after you initialize your connection with Firestore, for you to be able to write on it. Just save your HTML data into variables and change the collection and document names, for you to be able to use it.

In this article - Adding Data to a Cloud Firestore Database - you can find a full tutorial, on how to save data from HTML into Firestore.

Let me know if the information helped you!

Body:
I am currently working on a web app using firebase where a teacher can reserve rooms in a school. Here is the code so far:

app.js:

const roomList = document.querySelector('#room-list');
function renderRoom(doc){
    let li = document.createElement('li');
    let buildingNumber = document.createElement('spam');
    let floorNumber = document.createElement('span');
    let roomNumber = document.createElement('span');
    let block = document.createElement('span');
    let firstName = document.createElement('span');
    let lastName = document.createElement('span');
    li.setAttribute('data-id', doc.id);
    buildingNumber.textContent = 'Room: ' + doc.data().buildingNumber + '-' + doc.data().floorNumber + doc.data().roomNumber;
    block.textContent = 'Block: ' + doc.data().block;
    firstName.textContent = 'First Name: ' + doc.data().firstName;
    lastName.textContent = 'Last Name: ' + doc.data().lastName;
    li.appendChild(buildingNumber);
    li.appendChild(floorNumber);
    li.appendChild(roomNumber);
    li.appendChild(block);
    li.appendChild(firstName);
    li.appendChild(lastName);
    roomList.appendChild(li);
}
db.collection('rooms').where('buildingNumber', '==' , '5').where('floorNumber' , '==' , '1').onSnapshot(snapshot =>  {
    let changes = snapshot.docChanges();
    changes.forEach(change => {
        if(change.type == 'added'){
            renderRoom(change.doc);
        } else if (change.type == 'removed'){
            let li = roomList.querySelector('[data-id = ' + change.doc.id + ']');
            roomList.removeChild(li);
        }
    })
})

app.html:

<!DOCTYPE html>

    <link rel = "stylesheet" href = "Styles.css">

Select the room:

        <form id = "add-room-list"></form>

    </form>

This currently displays a room someone enters. I was wondering how you can add a checkbox to the left of each room so you can click on it and then click a button and it would record the selected room into firebase. Thanks.

Body:
First, you need to get the values from the checkbox into Javascript variables, so you can use them in your Firestore set. Once you have done that, your code to save the values into Firestore should be something like this:

// Add a new document in the collection
db.collection("<your_collection>").doc("<your_doc>").set({
    field1: value1
    field2: value2
    ...
})
.then(function() {
    console.log("Document successfully written!");
})
.catch(function(error) {
    console.error("Error writing document: ", error);
});

This code is untested and doesn't have your collection and documents names, but you should have it in your Javascript like this, after you initialize your connection with Firestore, for you to be able to write on it. Just save your HTML data into variables and change the collection and document names, for you to be able to use it.

In this article - Adding Data to a Cloud Firestore Database - you can find a full tutorial, on how to save data from HTML into Firestore.

Let me know if the information helped you!


问:
What is the best way to use Docker for Entity Framework core update with Postgres?

Background

I am building an API to hold user info in a Postgres DB, using dotnet core and EF core.

I do not think it has any impact on the question following but for a background explanation, I am also using IdentityServer4, and Npgsql package for Postgres access.

In local, everything works absolutely fine, I can update my schema as I want, and it all reflects correclty in the database. Now I would like to make this containers out of these to help new team members set up quickly.

Problem

The problem occurs when I try to update the schema right from the dotnet API container. Here are my dockerfiles :

First attempt with only dockerfile

API Dockerfile:

```<code>FROM mcr.microsoft.com/dotnet/core/sdk:3.1-alpine AS build-env

WORKDIR /app

# Explicitly ask for path to be added
ENV PATH="${PATH}:/root/.dotnet/tools"

RUN dotnet tool install --global dotnet-ef --version 3.1.3

# Copy csproj and restore as distinct layers
COPY *.csproj /app
RUN dotnet restore api.csproj

COPY . /app
RUN dotnet publish api.csproj -c Release -o out

# Run updates
RUN dotnet ef database update -c HelloApiDbContext
RUN dotnet ef database update -c ConfigurationDbContext

# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
COPY --from=build-env /app/out .

ENTRYPOINT ["dotnet", "api.dll"]
</code>```

Postgres Dockerfile :

```<code>FROM postgres:12-alpine AS build-env
WORKDIR /app

ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

# Expose the PostgreSQL port
EXPOSE 5432

# Add VOLUMEs to allow backup of config, logs and databases
VOLUME  ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]

# Set the default command to run when starting the container
CMD ["postgres"]
</code>```

Also my default configuration connection string looks like this:

```<code>"DefaultConnection": "Server=localhost;Database=docker;Port=32778;User id=docker;Password=docker"
</code>```

But it always results with :

```<code>Build started...
Build succeeded.
Npgsql.NpgsqlException (0x80004005): Exception while connecting
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (99): Address not available [::1]:32778
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
</code>```

I have tried several things.

Note

If I run the update from the Package Manager or my Powershell, with local EF, it works fine.

Second attempt with compose

I understood that the issue was coming from internal DNS from Docker container not being resolved.
I used other methods to link the two with the most promising one being a shell script following this post like so :

```<code>#!/bin/bash

set -e
run_cmd="dotnet run --server.urls http://*:80"

until dotnet ef database update -c HelloApiDbContext; do
>&2 echo "SQL Server is starting up"
sleep 1
done

>&2 echo "SQL Server is up - executing command"
exec $run_cmd
</code>```

And a docker-compose file :

```<code>version: '3.4'

networks:
  api-dev:
    driver: "bridge"

services:
  logic-api:
    image: project/api:latest
    depends_on:
     - "usersdb"
    build:
      context: ./api/
      dockerfile: dockerfile
    ports:
        - "5000:80"
    networks:
      - api-dev

  usersdb:
    image: usersdb:latest
    build:
      context: ./users-db/
      dockerfile: dockerfile
    ports:
      - "32778:5432"
    volumes:
      - db_volume:/var/lib/postgresql/data
    environment:
      POSGRES_USER: "docker"
      POSTGRES_PASSWORD : "docker"
      POSGRES_DB: "docker"
    networks:
      - api-dev
volumes:
  db_volume:
</code>```

And changed the entrypoint of the API dockerfile to make sure the Postgres db was up with DBeaver

before launching the update command like so :

```<code>EXPOSE 80/tcp
RUN chmod +x ./entrypoint.sh
CMD /bin/bash ./entrypoint.sh
</code>```

I also changed the default connection to be

```<code>"DefaultConnection": "Server=usersdb;Database=docker;Port=32778;User id=docker;Password=docker"
</code>```

Al attempts have failed an I keep running into this connection issue.

Questions

I have read in several posts that it is easier to manage SQL Migrations in prod with SQL scripts instead of EF auto migrations.
Should I abandon the idea to update from one container to another?

I would like to use EF completely though if possible.
Is there a way to make this connection work in a clean manner?

答:
Please update your connection string.

Change port number back to 5432

New connection string:

```<code>"DefaultConnection": "Server=usersdb;Database=docker;Port=5432;User id=docker;Password=docker"
</code>```

Justification:

API-DEV is a private network.

When working with docker trick is to understand what network are you into.

There are two networks in your example:

Your host/localcomputer

2nd API-DEV

API Dev will continue using default port 5432 for Postgres.

Further thoughts

I've read/heard on multiple places that docker for databases is not a good choice. Based on my limited knowledge I'd suggest that you use a native install of postgress

Docker-compose has a few limitations too. Kubernetes and YAML files solve creating infrastructure way better that docker-compose. Consider those as well.

Body:
Background

I am building an API to hold user info in a Postgres DB, using dotnet core and EF core.

I do not think it has any impact on the question following but for a background explanation, I am also using IdentityServer4, and Npgsql package for Postgres access.

In local, everything works absolutely fine, I can update my schema as I want, and it all reflects correclty in the database. Now I would like to make this containers out of these to help new team members set up quickly.

Problem

The problem occurs when I try to update the schema right from the dotnet API container. Here are my dockerfiles :

First attempt with only dockerfile

API Dockerfile:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-alpine AS build-env

WORKDIR /app

# Explicitly ask for path to be added
ENV PATH="${PATH}:/root/.dotnet/tools"

RUN dotnet tool install --global dotnet-ef --version 3.1.3

# Copy csproj and restore as distinct layers
COPY *.csproj /app
RUN dotnet restore api.csproj

COPY . /app
RUN dotnet publish api.csproj -c Release -o out

# Run updates
RUN dotnet ef database update -c HelloApiDbContext
RUN dotnet ef database update -c ConfigurationDbContext

# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
COPY --from=build-env /app/out .

ENTRYPOINT ["dotnet", "api.dll"]

Postgres Dockerfile :

FROM postgres:12-alpine AS build-env
WORKDIR /app

ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

# Expose the PostgreSQL port
EXPOSE 5432

# Add VOLUMEs to allow backup of config, logs and databases
VOLUME  ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]

# Set the default command to run when starting the container
CMD ["postgres"]

Also my default configuration connection string looks like this:

"DefaultConnection": "Server=localhost;Database=docker;Port=32778;User id=docker;Password=docker"

But it always results with :

Build started...
Build succeeded.
Npgsql.NpgsqlException (0x80004005): Exception while connecting
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (99): Address not available [::1]:32778
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

I have tried several things.

Note

If I run the update from the Package Manager or my Powershell, with local EF, it works fine.

Second attempt with compose

I understood that the issue was coming from internal DNS from Docker container not being resolved.
I used other methods to link the two with the most promising one being a shell script following this post like so :

#!/bin/bash

set -e
run_cmd="dotnet run --server.urls http://*:80"

until dotnet ef database update -c HelloApiDbContext; do
>&2 echo "SQL Server is starting up"
sleep 1
done

>&2 echo "SQL Server is up - executing command"
exec $run_cmd

And a docker-compose file :

version: '3.4'

networks:
  api-dev:
    driver: "bridge"

services:
  logic-api:
    image: project/api:latest
    depends_on:
     - "usersdb"
    build:
      context: ./api/
      dockerfile: dockerfile
    ports:
        - "5000:80"
    networks:
      - api-dev

  usersdb:
    image: usersdb:latest
    build:
      context: ./users-db/
      dockerfile: dockerfile
    ports:
      - "32778:5432"
    volumes:
      - db_volume:/var/lib/postgresql/data
    environment:
      POSGRES_USER: "docker"
      POSTGRES_PASSWORD : "docker"
      POSGRES_DB: "docker"
    networks:
      - api-dev
volumes:
  db_volume:

And changed the entrypoint of the API dockerfile to make sure the Postgres db was up with DBeaver

before launching the update command like so :

EXPOSE 80/tcp
RUN chmod +x ./entrypoint.sh
CMD /bin/bash ./entrypoint.sh

I also changed the default connection to be

"DefaultConnection": "Server=usersdb;Database=docker;Port=32778;User id=docker;Password=docker"

Al attempts have failed an I keep running into this connection issue.

Questions

I have read in several posts that it is easier to manage SQL Migrations in prod with SQL scripts instead of EF auto migrations.
Should I abandon the idea to update from one container to another?

I would like to use EF completely though if possible.
Is there a way to make this connection work in a clean manner?

Body:
Please update your connection string.

Change port number back to 5432

New connection string:

"DefaultConnection": "Server=usersdb;Database=docker;Port=5432;User id=docker;Password=docker"

Justification:

API-DEV is a private network.

When working with docker trick is to understand what network are you into.

There are two networks in your example:

Your host/localcomputer

2nd API-DEV

API Dev will continue using default port 5432 for Postgres.

Further thoughts

I've read/heard on multiple places that docker for databases is not a good choice. Based on my limited knowledge I'd suggest that you use a native install of postgress

Docker-compose has a few limitations too. Kubernetes and YAML files solve creating infrastructure way better that docker-compose. Consider those as well.


答:
If your

val

is a random value then you can use a dictionary like below

```<code>options = {1: -20, 2:-15,3:-10,4 : -5, 5:0,6 : 4,7 : 8, 8 : 12, 9 : 16 , 10 : 20}
val = options[val]
</code>```

Title: Better way of writing a long and simple if statement?

Body:
I am writing some custom values for a variable.
Is there a better way of writing this?

if val == 1:
    val = -20
elif val == 2:
    val = -15
elif val == 3:
    val = -10
elif val == 4:
    val = -5
elif val == 5:
    val = 0
elif val == 6:
    val = 4
elif val == 7:
    val = 8
elif val == 8:
    val = 12
elif val == 9:
    val = 16
elif val == 10:
    val = 20

Body:
If your

val

is a random value then you can use a dictionary like below

options = {1: -20, 2:-15,3:-10,4 : -5, 5:0,6 : 4,7 : 8, 8 : 12, 9 : 16 , 10 : 20}
val = options[val]


问:
System.InvalidOperationException: 'Databinding cannot occur unless a BindingContext or BindingContext Control has been specified.'
Problem Statement:

I have a Form A and here i am calling one API and it is taking few seconds to complete its operation. So, in this duration the user is closing the Form A. Due to this the object created in Form A gets disposed.

When the response comes back from API and try to call DataBinding() method it throws this exception: System.InvalidOperationException: 'Databinding cannot occur unless a BindingContext or BindingContext Control has been specified.'

Code:

```<code>public partial class FormA{
    private async void BindData(){
        var response = await _service.APICall(id);
        ultraComboEditor.DataSource = response;
        ultraComboEditor.DataBind(); //This throws the exception.
    }
}
</code>```

Question:

How to avoid this exception?

I can add a try catch block and avoid this exception, but it is not a
  good approach. So, is there any better solution to this?

答:
I found the perfect solution to this problem. The root cause of the problem was we are waiting for task to complete on form close.

Reference:
Awaiting Asynchronous function inside FormClosing Event

Solution:

The solution to my problem was to add a boolean variable(eg: _acyncClose) and set it to true on form closing event then after the API call I am checking for this property.

Code:

```<code>public partial class FormA{
    private bool _asyncClose = false;

    private async void BindData(){
        var response = await _service.APICall(id);
        if (_asyncClose) return;
        ultraComboEditor.DataSource = response;
        ultraComboEditor.DataBind(); //This throws the exception.
    }

    private void Form_Closing_Event(){
        _asyncClose = true;
    }
}
</code>```

Body:
Problem Statement:

I have a Form A and here i am calling one API and it is taking few seconds to complete its operation. So, in this duration the user is closing the Form A. Due to this the object created in Form A gets disposed.

When the response comes back from API and try to call DataBinding() method it throws this exception: System.InvalidOperationException: 'Databinding cannot occur unless a BindingContext or BindingContext Control has been specified.'

Code:

public partial class FormA{
    private async void BindData(){
        var response = await _service.APICall(id);
        ultraComboEditor.DataSource = response;
        ultraComboEditor.DataBind(); //This throws the exception.
    }
}

Question:

How to avoid this exception?

I can add a try catch block and avoid this exception, but it is not a
  good approach. So, is there any better solution to this?

Body:
I found the perfect solution to this problem. The root cause of the problem was we are waiting for task to complete on form close.

Reference:
Awaiting Asynchronous function inside FormClosing Event

Solution:

The solution to my problem was to add a boolean variable(eg: _acyncClose) and set it to true on form closing event then after the API call I am checking for this property.

Code:

public partial class FormA{
    private bool _asyncClose = false;

    private async void BindData(){
        var response = await _service.APICall(id);
        if (_asyncClose) return;
        ultraComboEditor.DataSource = response;
        ultraComboEditor.DataBind(); //This throws the exception.
    }

    private void Form_Closing_Event(){
        _asyncClose = true;
    }
}


问:
Make Image Text Appear And ReApear With Mouse How?
so what I am trying to do is make a text image appear when I click a sighn it should appear the exit and the image sprite and then when my mouse clicks the exit image it should delete both the image and the exit this is what I I tried but doesnt seem to work

what I have tried to do I doesnt seem to work

```<code>    for alrt in alerting:
        if event.type == pygame.MOUSEBUTTONDOWN:
                for exi in exiting:
                    exi.draw()
                for te in texting:
                    te.draw()
                for one in range(len(exiting)-1,-1,-1):
                    del exiting[one]
                for s in range(len(exiting)-1,-1,-1):
                    del exiting[s]

</code>```

答:
If the text is to be permanently visible after the mouse click, the text must be drawn in the application loop. Note that the MOUSEBUTTONDOWN event occurs only once.

sign_clicked = False

run = True
while run:

    # [...]

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

        if event.type == pygame.MOUSEBUTTONDOWN:

            if not sign_clicked:
                if # test if mouse is on sign
                    sign_clicked = True
            else:

                if # test if exit is clicked
                    # [...]

                if # test if the image is clicked
                    # [...]

    if sign_clicked:

        # draw exit and image
```

Body:
so what I am trying to do is make a text image appear when I click a sighn it should appear the exit and the image sprite and then when my mouse clicks the exit image it should delete both the image and the exit this is what I I tried but doesnt seem to work

what I have tried to do I doesnt seem to work

    for alrt in alerting:
        if event.type == pygame.MOUSEBUTTONDOWN:
                for exi in exiting:
                    exi.draw()
                for te in texting:
                    te.draw()
                for one in range(len(exiting)-1,-1,-1):
                    del exiting[one]
                for s in range(len(exiting)-1,-1,-1):
                    del exiting[s]