问:
What does this event mean, "Cancelling deletion of Pod", "TaintManagerEviction'
```<code>I1209 00:01:25.090381 10 event.go:294 "Event occurred" object="default/POD_NAME"
kind="Pod"
apiVersion=""
type="Normal"
reason="TaintManagerEviction"
message="Cancelling deletion of Pod default/POD_NAME"
</code>```

I've googled and tried to look for source code.

Body:
I1209 00:01:25.090381 10 event.go:294 "Event occurred" object="default/POD_NAME"
kind="Pod"
apiVersion=""
type="Normal"
reason="TaintManagerEviction"
message="Cancelling deletion of Pod default/POD_NAME"

I've googled and tried to look for source code.


来源: stackexchange

问:
ColdFusion insert multiple records checkboxes, not looping through hidden fields
I have a field with multiple checkboxes on it, dynamically populated from a database query.  For example, let's say there are 6 checkboxes, and I select 2 of them.  The insert code is working fine, but it only passes ONE TestCategoryID and ONE TestID, even though the checkbox options might be from different categories and all have different test numbers. If I include the hidden fields in the main query output within the form, then I get an error that says the number of fields and values don't match, and it doesn't insert anything. Here is my form.

```<code><form action="form_processor.cfm" method="post" name="testdefaults" id="testdefaults">
    <table width="50%" align="center">
    <cfoutput query="getMasterTests">
        <tr>
            <td>
            <input name="MasterID" type="checkbox" value="#MasterID#" />
            <span class="small-font">#TestCategoryID# #TestCategory# | #TestID# #SUBTEST# (#MasterID#)</span>
            </td>
        </tr>
    </cfoutput>
    </table>
    <div align="center" style="padding: 22px;">
      <input name="save" type="submit" class="myButton" value="Save Selected Tests as YOUR Default Tests" />
    </div>
    <cfoutput>
    <input name="TestCategoryID" type="hidden" value="#getMasterTests.TestCategoryID#" />
    <input name="TestID" type="hidden" value="#getMasterTests.TestID#" />
    <input name="userID" type="hidden" value="#getUser.RegistrationID#" />
    </cfoutput>
    <input type="hidden" name="MM_InsertRecord" value="testdefaults" />
</form>
</code>```

Here is my insert code:

```<code><cfloop INDEX="Checked_ITEM" LIST="#Form.MasterID#">
    <cfquery Name="add" DataSource="mvqs">
        INSERT INTO tblXLU_Test_Defaults (Default_User_ID, TestCategoryID, TestID, MasterID)
        VALUES (#form.UserID#, #Form.TestCategoryID#, #Form.TestID#, '#Checked_ITEM#')
    </cfquery>
</cfloop>
</code>```

I need to be able to loop through not only the Master ID of the checkbox, which works, but also the TestCategoryID and TestID fields as well, and I'm stumped. Any help would be greatly appreciated.

Thank you.

ContentLicense: CC BY-SA 4.0

Body:
I have a field with multiple checkboxes on it, dynamically populated from a database query.  For example, let's say there are 6 checkboxes, and I select 2 of them.  The insert code is working fine, but it only passes ONE TestCategoryID and ONE TestID, even though the checkbox options might be from different categories and all have different test numbers. If I include the hidden fields in the main query output within the form, then I get an error that says the number of fields and values don't match, and it doesn't insert anything. Here is my form.

<form action="form_processor.cfm" method="post" name="testdefaults" id="testdefaults">

    <cfoutput query="getMasterTests">

            <input name="MasterID" type="checkbox" value="#MasterID#" />
            #TestCategoryID# #TestCategory# | #TestID# #SUBTEST# (#MasterID#)

    </cfoutput>

      <input name="save" type="submit" class="myButton" value="Save Selected Tests as YOUR Default Tests" />

    <cfoutput>
    <input name="TestCategoryID" type="hidden" value="#getMasterTests.TestCategoryID#" />
    <input name="TestID" type="hidden" value="#getMasterTests.TestID#" />
    <input name="userID" type="hidden" value="#getUser.RegistrationID#" />
    </cfoutput>
    <input type="hidden" name="MM_InsertRecord" value="testdefaults" />
</form>

Here is my insert code:

<cfloop INDEX="Checked_ITEM" LIST="#Form.MasterID#">
    <cfquery Name="add" DataSource="mvqs">
        INSERT INTO tblXLU_Test_Defaults (Default_User_ID, TestCategoryID, TestID, MasterID)
        VALUES (#form.UserID#, #Form.TestCategoryID#, #Form.TestID#, '#Checked_ITEM#')
    </cfquery>
</cfloop>

I need to be able to loop through not only the Master ID of the checkbox, which works, but also the TestCategoryID and TestID fields as well, and I'm stumped. Any help would be greatly appreciated.

Thank you.


问:
using rollapply function from zoo package in R with na.rm argument
I would like to use the rollapply function from the zoo package in R to calculate a moving IQR, but this fails when missing data (NA's) are reached in my data series.

```<code>data_series <- c(4,7,4,7,3,6,5,8,5,NA,9,0,5,8,1,3,6,5)
roll_iqr <- rollapply(data_series, width = 5, fill = NA, FUN = IQR)

Error in quantile.default(as.numeric(x), c(0.25, 0.75), na.rm = na.rm,  :
missing values and NaN's not allowed if 'na.rm' is FALSE
</code>```

Is there a way to tell the rollapply function to include the na.rm = T argument that would normally be part of the IQR function?

Body:
I would like to use the rollapply function from the zoo package in R to calculate a moving IQR, but this fails when missing data (NA's) are reached in my data series.

data_series <- c(4,7,4,7,3,6,5,8,5,NA,9,0,5,8,1,3,6,5)
roll_iqr <- rollapply(data_series, width = 5, fill = NA, FUN = IQR)

Error in quantile.default(as.numeric(x), c(0.25, 0.75), na.rm = na.rm,  :
missing values and NaN's not allowed if 'na.rm' is FALSE

Is there a way to tell the rollapply function to include the na.rm = T argument that would normally be part of the IQR function?


问:
Not matching tradingview
I am using TradingView as reference for EMA.

As of 9th December, EMA 100 for ABB (Indian Exchange) is 2962.25. But when I use pandas ta I get 2965.44.

Similarly, 200 ema should be 2720.93 but I get 2685.57

```<code>import yfinance as yf
import pandas_ta as ta

x = yf.download('ABB.NS', start = "2021-12-08", progress = False)['Close']

ema100 = ta.ema(x,100)[-1]
ema200 = ta.ema(x, 200)[-1]
</code>```

Title: Not matching tradingview

Body:
I am using TradingView as reference for EMA.

As of 9th December, EMA 100 for ABB (Indian Exchange) is 2962.25. But when I use pandas ta I get 2965.44.

Similarly, 200 ema should be 2720.93 but I get 2685.57

import yfinance as yf
import pandas_ta as ta

x = yf.download('ABB.NS', start = "2021-12-08", progress = False)['Close']

ema100 = ta.ema(x,100)[-1]
ema200 = ta.ema(x, 200)[-1]


问:
urllib3 and requests, fix status code 403 in urllib3, requests work good as well
When I run the code only requests code work and it's return status code 200. and urllib3 fail, it return status code 403. I want urllib3 will return the same as requests results, here are the following codes:

requests code:

import requests

proxies = {"http":"http://username:password@host:port"} #proxy protocol

r = requests.get('https://www.examples.com', proxies=proxies) #make the request

print(r.status_code) #return status code 200, successful request
```
<p>urllib3 code:</p>
<pre class="lang-py prettyprint-override"><code>import urllib3

auth_headers = urllib3.make_headers(proxy_basic_auth='username:password') #proxy authorization build

Proxy = urllib3.ProxyManager(proxy_url="http://host:port", proxy_headers=auth_headers)

url = 'https://www.example.com/'

r = Proxy.request('GET', url) #make the request

print(r.status) #return status code 403, I want it to return status code 200 like the same as the requests code.
</code>```

Edited: It's also work good with PoolManager()

Body:
When I run the code only requests code work and it's return status code 200. and urllib3 fail, it return status code 403. I want urllib3 will return the same as requests results, here are the following codes:

requests code:

import requests

proxies = {"http":"http://username:password@host:port"} #proxy protocol

r = requests.get('https://www.examples.com', proxies=proxies) #make the request

print(r.status_code) #return status code 200, successful request

urllib3 code:

import urllib3

auth_headers = urllib3.make_headers(proxy_basic_auth='username:password') #proxy authorization build

Proxy = urllib3.ProxyManager(proxy_url="http://host:port", proxy_headers=auth_headers)

url = 'https://www.example.com/'

r = Proxy.request('GET', url) #make the request

print(r.status) #return status code 403, I want it to return status code 200 like the same as the requests code.

Edited: It's also work good with PoolManager()


问:
how can we tell dagitty in R to not include a latent variable in the set of all the adjustment sets?
I am using dagitty package in R. I have a DAG as follows where U is latent:

```<code>library(dagitty)
dag <- dagitty("
dag {
U [latent]
U -> Z1
Z1 -> Z2
Z2 -> Y
U -> X
X -> Y
}
")
</code>```

When I call the  adjustmentSets(x = dag, exposure = "X", outcome = "Y" , type = "all") function, this is the results:

{U}
{Z1}
{U, Z1}
{Z2}
{U, Z2}
{Z1, Z2}
{U, Z1, Z2 }

the results include U. How can I not have U in the results without changing the dag?

I expect it to not show U in the results. I tried changing the DAG as follows:

```<code>dag <- dagitty("
dag {
Z1 -> Z2
Z2 -> Y
Z1 <-> X
X -> Y
}
")
</code>```

And I get the following results which is what I expected:

{Z1 }
{Z2 }
{Z1, Z2 }

But I don't want to manually change the results, as I have a really large graph and I want to get the right results without changing the graph structure.

Body:
I am using dagitty package in R. I have a DAG as follows where U is latent:

library(dagitty)
dag <- dagitty("
dag {
U [latent]
U -> Z1
Z1 -> Z2
Z2 -> Y
U -> X
X -> Y
}
")

When I call the  adjustmentSets(x = dag, exposure = "X", outcome = "Y" , type = "all") function, this is the results:

{U}
{Z1}
{U, Z1}
{Z2}
{U, Z2}
{Z1, Z2}
{U, Z1, Z2 }

the results include U. How can I not have U in the results without changing the dag?

I expect it to not show U in the results. I tried changing the DAG as follows:

dag <- dagitty("
dag {
Z1 -> Z2
Z2 -> Y
Z1 <-> X
X -> Y
}
")

And I get the following results which is what I expected:

{Z1 }
{Z2 }
{Z1, Z2 }

But I don't want to manually change the results, as I have a really large graph and I want to get the right results without changing the graph structure.


问:
Only have 1 scrollbar for entire page
I've split the screen horizontally into 2 sections (left & right)

However, the 2 scrollbars are appearing on the right side of each section

How can we make it so that there's only 1 scrollbar for entire page?

Thanks!

I've wrapped the left & right class with a class named split

```<code>.split {
  height: 70%;
  width: 50%;
  position: fixed;
  z-index: 1;
  top: 100px;
  overflow-x: hidden;
  //overflow-y: hidden;
  padding-top: 300px;
  display:flex;

}

.left {
  left: 0;
  top: 80px;
}

.right {
  right: 0;
  top: 80px;
}

</code>```

Title: Only have 1 scrollbar for entire page

Body:
I've split the screen horizontally into 2 sections (left & right)

However, the 2 scrollbars are appearing on the right side of each section

How can we make it so that there's only 1 scrollbar for entire page?

Thanks!

I've wrapped the left & right class with a class named split

.split {
  height: 70%;
  width: 50%;
  position: fixed;
  z-index: 1;
  top: 100px;
  overflow-x: hidden;
  //overflow-y: hidden;
  padding-top: 300px;
  display:flex;

}

.left {
  left: 0;
  top: 80px;
}

.right {
  right: 0;
  top: 80px;
}


问:
MS Access Sum and IIF expression
I'm with a non-profit. We divide the state up into 16 regions for administrative purposes. I'm trying to find out how many members live in each region. We have 4 different types of members too. There's a table that lists all the members. There is also a table in which we have listed all the towns in the state and put in which of our regions the town is in. For the first member type the record has the value "1" in the TYPE field. I'm trying to write an expression that basically says this. If the TYPE field has a "1" in it, then the condition is true, return 1. Else return 0. Then sum up all the ones.

I didn't build the database or the query. This is the expression that was already there: INDIVIDUAL: Sum(IIf([Membership.TYPE]=1,1,0)) The sum that it comes up with just doesn't make sense.

Edit: I hope I did this right.  Here is a table showing what information the query returns except for the 502 and the 96 which I put there as a check.  The values in that one column add up to 502 but they should add up to 674.  The 96 should be 113.
enter image description here

Title: MS Access Sum and IIF expression


问:
env: TX - row lock contention during update in RAC
My first posting on stackoverflow :)

I observed a lot of latency yesterday in this 4 node RAC. Update statement:

```<code>UPDATE ACT_RU_JOB
   SET REV_ = :1,
       LOCK_EXP_TIME_ = :2,
       LOCK_OWNER_ = :3,
       DUEDATE_ = :4,
       PROCESS_INSTANCE_ID_ = :5,
       EXCLUSIVE_ = :6
WHERE ID_ = :7 AND REV_ = :8
</code>```

There were 8 sessions each showing the same update and wait event name enq: TX - row lock contention.

The AWR report shows it was the top SQL waited by elapsed time: enter image description here

This is a third party application, so changing code is not practical. How do I resolve this wait event? This happens when the application is busier, does not happen in quiet periods.

For the table in question, the AWR report reports some ITL waits where VALUE is 7 and %CAPTURE is 9.86%. Does that justify increasing INITRAN of the table from 1 to a higher value?

Any help will be appreciated.

There was a thought of killing one of the sessions, but simply waiting resolved the issue.

Body:
My first posting on stackoverflow :)

I observed a lot of latency yesterday in this 4 node RAC. Update statement:

UPDATE ACT_RU_JOB
   SET REV_ = :1,
       LOCK_EXP_TIME_ = :2,
       LOCK_OWNER_ = :3,
       DUEDATE_ = :4,
       PROCESS_INSTANCE_ID_ = :5,
       EXCLUSIVE_ = :6
WHERE ID_ = :7 AND REV_ = :8

There were 8 sessions each showing the same update and wait event name enq: TX - row lock contention.

The AWR report shows it was the top SQL waited by elapsed time: enter image description here

This is a third party application, so changing code is not practical. How do I resolve this wait event? This happens when the application is busier, does not happen in quiet periods.

For the table in question, the AWR report reports some ITL waits where VALUE is 7 and %CAPTURE is 9.86%. Does that justify increasing INITRAN of the table from 1 to a higher value?

Any help will be appreciated.

There was a thought of killing one of the sessions, but simply waiting resolved the issue.


问:
BigQuery sessions count not matching Google Analytics
What's the best way to get the sessions count to get as close as possible to what's in Google Analytics? (I'm still using GA360.)

This is my current query for page-level session figures:

```<code>SELECT
    date,
    COUNT(DISTINCT IF(totals.visits=1, CONCAT(fullVisitorId, CAST(visitId AS STRING)), NULL) ) as Sessions,
    h.page.pageTitle,
    h.page.hostname,
    channelgrouping as default_channel_grouping,
    concat("https://", h.page.hostname, h.page.pagePathLevel1, REGEXP_REPLACE(h.page.pagePathLevel2, '^.', ''), REGEXP_REPLACE(h.page.pagePathLevel3, '^.', '')) as page_path
  FROM
    `dive-ga.projectnumber.ga_sessions_*`,
    UNNEST(hits) AS h
  WHERE
    _table_suffix BETWEEN '20210901'
    AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))
  GROUP BY
    date, h.page.pageTitle, h.page.hostname, channelgrouping, concat("https://", h.page.hostname, h.page.pagePathLevel1, REGEXP_REPLACE(h.page.pagePathLevel2, '^.', ''), REGEXP_REPLACE(h.page.pagePathLevel3, '^.', ''))
</code>```

I understand that Google Analytics is only showing sessions where there is an event fired. And I've tried looking at all the different session calculations mentioned in the top response in this post.

But the sessions figures are still so off that when I look at YoY figures I can see an increase when looking at BigQuery, but GA will show a decline.

Anything I should be changing in this query?

Body:
What's the best way to get the sessions count to get as close as possible to what's in Google Analytics? (I'm still using GA360.)

This is my current query for page-level session figures:

SELECT
    date,
    COUNT(DISTINCT IF(totals.visits=1, CONCAT(fullVisitorId, CAST(visitId AS STRING)), NULL) ) as Sessions,
    h.page.pageTitle,
    h.page.hostname,
    channelgrouping as default_channel_grouping,
    concat("https://", h.page.hostname, h.page.pagePathLevel1, REGEXP_REPLACE(h.page.pagePathLevel2, '^.', ''), REGEXP_REPLACE(h.page.pagePathLevel3, '^.', '')) as page_path
  FROM
    `dive-ga.projectnumber.ga_sessions_*`,
    UNNEST(hits) AS h
  WHERE
    _table_suffix BETWEEN '20210901'
    AND FORMAT_DATE('%Y%m%d',DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))
  GROUP BY
    date, h.page.pageTitle, h.page.hostname, channelgrouping, concat("https://", h.page.hostname, h.page.pagePathLevel1, REGEXP_REPLACE(h.page.pagePathLevel2, '^.', ''), REGEXP_REPLACE(h.page.pagePathLevel3, '^.', ''))

I understand that Google Analytics is only showing sessions where there is an event fired. And I've tried looking at all the different session calculations mentioned in the top response in this post.

But the sessions figures are still so off that when I look at YoY figures I can see an increase when looking at BigQuery, but GA will show a decline.

Anything I should be changing in this query?


问:
Dereferencing a pointer by multiple threads
In the example below, suppose I have a multithreaded queue i.e. supports multiple writes and reads from different threads (e.g. using mutex). We can see that 1. the pointer this as well as 2. the shared pointer m_mulque are passed to the readers and writers and my question is: Dereferencing the pointers this and m_mulque is thread safe or not? In other words is my following code thread safe or not meaning should I worry about any undefined behaviour if I run this please?

```<code>#include <mutex>
#include <queue>

struct multithreaded_queue
{
    void push(const std::size_t i)
    {
        std::lock_guard lock(m_mutex);
        m_queue.push(i);
    };

    void try_pop()
    {
        std::lock_guard lock(m_mutex);
        m_queue.pop();
    };

private:
    std::queue<std::size_t> m_queue;
    mutable std::mutex m_mutex;
};
</code>```
```<code>class example
{
public:
    example()
    {
        m_mulque = std::make_shared<multithreaded_queue>();
    };

    void run()
    {
        auto writer = [this]()
        {
            for (std::size_t i = 0; i < 1000; i++)
            {
                m_mulque->push(i);
            };
        };

        auto reader = [this]()
        {
            for (std::size_t i = 0; i < 1000; i++)
            {
                m_mulque->try_pop();
            };
        };

        std::thread writer1(writer);
        std::thread reader1(reader);
        std::thread reader2(reader);

        writer1.join();
        reader1.join();
        reader2.join();
    };

private:
    std::shared_ptr<multithreaded_queue> m_mulque;
};
</code>```
```<code>int main(int argc, char* argv[])
{
    example ex;
    ex.run(); //Is this thread safe to call?
};
</code>```

Body:
In the example below, suppose I have a multithreaded queue i.e. supports multiple writes and reads from different threads (e.g. using mutex). We can see that 1. the pointer this as well as 2. the shared pointer m_mulque are passed to the readers and writers and my question is: Dereferencing the pointers this and m_mulque is thread safe or not? In other words is my following code thread safe or not meaning should I worry about any undefined behaviour if I run this please?

#include <mutex>
#include <queue>

struct multithreaded_queue
{
    void push(const std::size_t i)
    {
        std::lock_guard lock(m_mutex);
        m_queue.push(i);
    };

    void try_pop()
    {
        std::lock_guard lock(m_mutex);
        m_queue.pop();
    };

private:
    std::queue<std::size_t> m_queue;
    mutable std::mutex m_mutex;
};

class example
{
public:
    example()
    {
        m_mulque = std::make_shared<multithreaded_queue>();
    };

    void run()
    {
        auto writer = [this]()
        {
            for (std::size_t i = 0; i < 1000; i++)
            {
                m_mulque->push(i);
            };
        };

        auto reader = [this]()
        {
            for (std::size_t i = 0; i < 1000; i++)
            {
                m_mulque->try_pop();
            };
        };

        std::thread writer1(writer);
        std::thread reader1(reader);
        std::thread reader2(reader);

        writer1.join();
        reader1.join();
        reader2.join();
    };

private:
    std::shared_ptr<multithreaded_queue> m_mulque;
};

int main(int argc, char* argv[])
{
    example ex;
    ex.run(); //Is this thread safe to call?
};


问:
How and where should I define types for an SDK / wrapper of a third party API?
I'm writing an SDK for an API that doesn't currently have one. I want to write it in TypeScript to make it easier to use, but I'm struggling with how and where to documents the types for the values the API returns.

For example, the endpoint /accountInfo returns an object with ~40 properties, some of which are arrays of objects that could have their own interfaces. Defining these types right in my .ts file feels very messy, but I can't figure out the right place to create them. I went down the path of creating a .d.ts file, with a namespace for each endpoint, but I can't figure out how to properly import those types and use them. I see a lot of people saying you shouldn't be writing your own .d.ts definitions unless you're writing them for a JS module... but is this kind of the equivalent?

Any advice on how to implement types for this kind of project is appreciated.


问:
Sending emails using app with flutter using SMPT
I have tried to send emails using app, that app is built using flutter framework. There is no error while it is running but emails are not sent. This is my code.</p>
```<code>**send email function**

 Future sendEmail(subject,msg) async{
    final user = await GoogleAuthApi.signIn();

    if(user == null) return;
    final email = user.email;
    final auth = await user.authentication;
    final token =auth.accessToken!;

    final smtpServer = gmailRelaySaslXoauth2(email, token);
    final message = Message()
        ..from = Address(email,'test')
        ..recipients = ["test@gmail.com"]
        ..subject = subject.toString()
        ..text=msg.toString();

    try{
      await send(message,smtpServer);
      showSnackBar('Sent email successfully!');
    }on MailerException catch(e){
      print("hi==$e");
    }
  }

class GoogleAuthApi{
  static final _googleSignIn = GoogleSignIn(scopes: ['https://mail.google.com/']);

  static Future<GoogleSignInAccount?> signIn() async{
    if(await _googleSignIn.isSignedIn()){
      return _googleSignIn.currentUser;
    }else {
      return await _googleSignIn.signIn();
    }
  }
}
</code>```

Body:
I have tried to send emails using app, that app is built using flutter framework. There is no error while it is running but emails are not sent. This is my code.

**send email function**

 Future sendEmail(subject,msg) async{
    final user = await GoogleAuthApi.signIn();

    if(user == null) return;
    final email = user.email;
    final auth = await user.authentication;
    final token =auth.accessToken!;

    final smtpServer = gmailRelaySaslXoauth2(email, token);
    final message = Message()
        ..from = Address(email,'test')
        ..recipients = ["test@gmail.com"]
        ..subject = subject.toString()
        ..text=msg.toString();

    try{
      await send(message,smtpServer);
      showSnackBar('Sent email successfully!');
    }on MailerException catch(e){
      print("hi==$e");
    }
  }

class GoogleAuthApi{
  static final _googleSignIn = GoogleSignIn(scopes: ['https://mail.google.com/']);

  static Future<GoogleSignInAccount?> signIn() async{
    if(await _googleSignIn.isSignedIn()){
      return _googleSignIn.currentUser;
    }else {
      return await _googleSignIn.signIn();
    }
  }
}


问:
Picture can't be displayed when adding picture to copied table using python-docx
I'm using python-docx to edit an existing word file. I've created a simpler case where it also fails starting with a blank document. Adding a picture to a cell in a table works just as expected. But if I want to copy that table, there seems to be a problem when I add an image to the new table. I've looked elsewhere, but this problem seems to be unique to copied tables only.

from copy import deepcopy
from docx import Document

doc = Document()

table1 = doc.add_table(rows=2, cols=2)
table1.style = 'TableGrid'

table2 = deepcopy(table)
table2._tbl = deepcopy(table1._tbl)

p = doc.add_paragraph()
p._p.addnext(table2._tbl)

# Add image to table 1
cell = table1.rows[0].cells[0]
cell.paragraphs[0].add_run().add_picture("picture.png", width=Cm(10))

# Add image to table 2
cell = table2.rows[0].cells[0]
cell.paragraphs[0].add_run().add_picture("picture.png", width=Cm(10))

doc.save("t.docx")
```

Problem: If I add the same image to both, it will appear correct. If I add it to only table 1, it also works. But if I add it to the copy, then it fails and looks like this:

It seems to be something that is different in the second, copied table. I know it looks like a hack the way it was created. I did it this way because, in my original document, the table is quite complex and needs to be duplicated for each case.

(Edit: added missing deepcopyimport)

Body:
I'm using python-docx to edit an existing word file. I've created a simpler case where it also fails starting with a blank document. Adding a picture to a cell in a table works just as expected. But if I want to copy that table, there seems to be a problem when I add an image to the new table. I've looked elsewhere, but this problem seems to be unique to copied tables only.

from copy import deepcopy
from docx import Document

doc = Document()

table1 = doc.add_table(rows=2, cols=2)
table1.style = 'TableGrid'

table2 = deepcopy(table)
table2._tbl = deepcopy(table1._tbl)

p = doc.add_paragraph()
p._p.addnext(table2._tbl)

# Add image to table 1
cell = table1.rows[0].cells[0]
cell.paragraphs[0].add_run().add_picture("picture.png", width=Cm(10))

# Add image to table 2
cell = table2.rows[0].cells[0]
cell.paragraphs[0].add_run().add_picture("picture.png", width=Cm(10))

doc.save("t.docx")

Problem: If I add the same image to both, it will appear correct. If I add it to only table 1, it also works. But if I add it to the copy, then it fails and looks like this:

It seems to be something that is different in the second, copied table. I know it looks like a hack the way it was created. I did it this way because, in my original document, the table is quite complex and needs to be duplicated for each case.

(Edit: added missing deepcopyimport)


问:
ClosedXML (Windows): Unable to find font Tahoma or fallback font Microsoft Sans Serif
I'm facing an issue to produce an excel file in local machine through a SQL Server job using ClosedXML in a script task (C#). The job under a service account and it has admin privilege in local machine. Below is the error it is producing.

"Unable to find font Tahoma or fallback font Microsoft Sans Serif. Install missing fonts or specify a different fallback font through 'LoadOptions.DefaultGraphicEngine = new DefaultGraphicEngine("Fallback font name")'.".

I've checked the fonts (Tahoma and Microsoft Sans Serif) exists in the C:\Windows\Font (Based on the font location mentioned in https://github.com/SixLabors/Fonts/blob/main/src/SixLabors.Fonts/SystemFontCollection.cs#L27)

However, when I run the same code in Visual Studio it can successfully produce Excel file without complaining about anything.

My assumption is that it is not permission related as I can produce the Excel files under my account through visual studio but not from SQL Server.

Note: All the activity to produce the Excel file is happening locally (no remote call). Any help or suggestion is appreciated.

Add the LoadOptions.DefaultGraphicEngine = new DefaultGraphicEngine("Fallback font name") in the code. I have selected <fallback font name> that exists in the below directories:                    @"%SYSTEMROOT%\Fonts",@"%APPDATA%\Microsoft\Windows\Fonts",@"%LOCALAPPDATA%\Microsoft\Windows\Fonts".

Copy the Tahoma and Microsoft Sans Serif in those folders.

Checked any deny permission exists for the service account and my account.

Run the job both Service account and my account from SQL Server.


问:
Submit html form, stay on same page with added success content
Using html web-to-case form generated by salesforce, I want users to submit, stay on the same page and see a success message. If I add the salesforce server url to the form, it gets sent to the server but the user is redirected from the form page to that url.  I've tried:

·targeting an iframe in the form tag but it doesn't submit to the
server

·using an event listener and 'setTimeout(() => form.submit()', but
that also redirects to server url (or refreshes the page if I specify a return url) (see Success Message display on submit html form)

·using ajax to send the form data but that doesn't post to the
server or do anything:

```<code> $( "form" ).on( "submit", function(e) {
 var dataString = $(this).serialize();
 // alert(dataString); return false;
 $.ajax({
 type: "POST",
 url: "https://xxx-uat1.sandbox.my.salesforce.com/servlet/servlet.WebToCase?
 encoding=UTF-8",
 data: dataString,
 success: function () {
 $("#contact_form").html("<div id='message'></div>");
 $("#message")
   .html("<h2>Contact Form Submitted!</h2>")
   .append("<p>We will be in touch soon.</p>")
   .hide()
   .fadeIn(1500, function () {
     $("#message").append(
       "<img id='checkmark' src='images/check.png' />"
     );
   });
   }
 });

e.preventDefault();
});
</code>```

Body:
Using html web-to-case form generated by salesforce, I want users to submit, stay on the same page and see a success message. If I add the salesforce server url to the form, it gets sent to the server but the user is redirected from the form page to that url.  I've tried:

·targeting an iframe in the form tag but it doesn't submit to the
server

·using an event listener and 'setTimeout(() => form.submit()', but
that also redirects to server url (or refreshes the page if I specify a return url) (see Success Message display on submit html form)

·using ajax to send the form data but that doesn't post to the
server or do anything:

 $( "form" ).on( "submit", function(e) {
 var dataString = $(this).serialize();
 // alert(dataString); return false;
 $.ajax({
 type: "POST",
 url: "https://xxx-uat1.sandbox.my.salesforce.com/servlet/servlet.WebToCase?
 encoding=UTF-8",
 data: dataString,
 success: function () {
 $("#contact_form").html("

");
 $("#message")
   .html("
Contact Form Submitted!
")
   .append("
We will be in touch soon.
")
   .hide()
   .fadeIn(1500, function () {
     $("#message").append(
       ""
     );
   });
   }
 });

e.preventDefault();
});


问:
How to exit block selection mode in Texstudio via keyboard?
Referring to the Texstudio user manual section 2.7.1 Manipulating tables there is the shortcut Ctrl+Alt+Shift to enter block selection mode.

Is there a way to exit that block selection mode (i.e. go back to only one cursor), using only the keyboard?

Unlike other editors, Esc does not work.


问:
Xamarin Binding for Brother Printer BRLMPrinterKit.xcframework with XCODE 14
I need to create a binding for the Brother BRLMPrinterKit.xcframework version 4.61 or any version 4, but my MacBook with Ventura OS loaded on it only allows me to install XCODE 14.

When I try run Objective Sharpie on the Brother Framework it errors out with the following message:

iphoneos15.0 SDK is required.

XCODE 14 only has iphoneos 16.0 SDK.

I tried installing XCODE 13, but it will not install on Ventura MacOS.

Any Ideas?


问:
pip build-system has unpinned dependencies that break on update
I'm looking to pin Python dependencies installed as part of the pip build system. Here is the scenario I'm working with:

I'm using a requirements file to install a 3rd party package (from a git+ssh source, but I doubt that matters).

i.e. requirements.txt

```<code>git+ssh://git@gitremote/some/path/included-project.git@1.2.3#egg=included-project
</code>```

Then, of course:

```<code>pip install -r requirements.txt
</code>```

That "included-project" has a pyproject.toml that looks like this:

```<code>[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
</code>```

Because poetry is not pinned, it upgrades to the newest version. However, the new version of poetry appears to be pulling in keyring, which pulls in SecretStorage, which pulls in cryptography... none of which are pinned. The new version of cryptography that's pulled in more recently started breaking my build because it's missing Rust.

I want my build to be deterministic, so I'd like to pin all the dependencies that poetry installs as part of the "build-system". This build-system and pep517 is new to me; my understanding is that it creates a virtualenv of sorts just to install the build-backend (poetry and deps) and then abandons that after the build is done. And as I understand it, that virtualenv is different than the virtualenv that is created by the normal install.

As such, I'm not sure how to pin packages inside of that temporary virtualenv that build-system creates. How can I do this?

Body:
I'm looking to pin Python dependencies installed as part of the pip build system. Here is the scenario I'm working with:

I'm using a requirements file to install a 3rd party package (from a git+ssh source, but I doubt that matters).

i.e. requirements.txt

git+ssh://git@gitremote/some/path/included-project.git@1.2.3#egg=included-project

Then, of course:

pip install -r requirements.txt

That "included-project" has a pyproject.toml that looks like this:

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"

Because poetry is not pinned, it upgrades to the newest version. However, the new version of poetry appears to be pulling in keyring, which pulls in SecretStorage, which pulls in cryptography... none of which are pinned. The new version of cryptography that's pulled in more recently started breaking my build because it's missing Rust.

I want my build to be deterministic, so I'd like to pin all the dependencies that poetry installs as part of the "build-system". This build-system and pep517 is new to me; my understanding is that it creates a virtualenv of sorts just to install the build-backend (poetry and deps) and then abandons that after the build is done. And as I understand it, that virtualenv is different than the virtualenv that is created by the normal install.

As such, I'm not sure how to pin packages inside of that temporary virtualenv that build-system creates. How can I do this?


问:
Writing out CSS menus on fly as I process an FireFox export html file. Post 60329925 seems to answer my issue but has a problem
I am reading a FireFox exported HTML data file and from it creating a HTML file that I can use to access my FF links.  I will then use existing FF data structure (minus links) in the toolbar to place new links which will be programmaticly added to my HTML file

As i read the FF file I am writing out pure CSS HTML menus with links as items in a list.
I have everything working, but with sub-menus expanding to right and I quickly run out of screen room once I am deeper than two levels deep.

I had decided I needed expand vertically and in searching for a solution I found post below that does exactly what I want to accomplish and wanted to use as bases for a re-write of my code.

CSS vertical multi level dropdown menu issue

This answer has one problem.  Dropdown1 has 4 associated items and a sub-menu but only the sub-menu and its contents are accessible, I can not access Items 1 through 4 associated with it. Can not move mouse directly (sub-menu expands) to them and can not mouse downward past Submenu1.

Not sure if I am missing something being unable to access those or if this is how the code was written and this was missed.  Hoping someone could help me out with this.


问:
how can i add mat-row in mat-table by using something like MsWord insertion has onHover

i tried to push some type of expty row onHover but it doesnt work


问:
Error when trying to use playsound to play music
I'm trying to play sound using playsound. Here is the code I have.
playsound('Chris Christodoulou - Coalescence Risk of Rain (2013).mp3')
When it gets to this code though, I get this error.

```<code>Traceback (most recent call last):
  File "main.py", line 19, in <module>
    playsound('Chris Christodoulou - Coalescence Risk of Rain (2013).mp3')
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 254, in <lambda>
    playsound = lambda sound, block = True: _playsoundAnotherPython('/usr/bin/python3', sound, block, macOS = False)
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 229, in _playsoundAnotherPython
    t.join()
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 218, in join
    raise self.exc
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 211, in run
    self.ret = self._target(*self._args, **self._kwargs)
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 226, in <lambda>
    t = PropogatingThread(target = lambda: check_call([otherPython, playsoundPath, _handlePathOSX(sound) if macOS else sound]))
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 359, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 340, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 858, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 1704, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/python3'
</code>```

Can you help me understand what this means and how I can fix this?

Body:
I'm trying to play sound using playsound. Here is the code I have.
playsound('Chris Christodoulou - Coalescence Risk of Rain (2013).mp3')
When it gets to this code though, I get this error.

Traceback (most recent call last):
  File "main.py", line 19, in <module>
    playsound('Chris Christodoulou - Coalescence Risk of Rain (2013).mp3')
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 254, in <lambda>
    playsound = lambda sound, block = True: _playsoundAnotherPython('/usr/bin/python3', sound, block, macOS = False)
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 229, in _playsoundAnotherPython
    t.join()
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 218, in join
    raise self.exc
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 211, in run
    self.ret = self._target(*self._args, **self._kwargs)
  File "/home/runner/CrushingUntriedSet/venv/lib/python3.8/site-packages/playsound.py", line 226, in <lambda>
    t = PropogatingThread(target = lambda: check_call([otherPython, playsoundPath, _handlePathOSX(sound) if macOS else sound]))
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 359, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 340, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 858, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 1704, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/python3'

Can you help me understand what this means and how I can fix this?


问:
Update and Delete the nested object in Entity Framework Core 7
I got this error, when I wanted to update product object:

System.InvalidOperationException: The instance of entity type 'Product' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

How can I  solve it?

ProductsController

```<code>[HttpPut("update/{id}")]
public async Task<ActionResult<int>> updateProduct(int id, [FromBody] ProductToUpdateDto updatingProduct)
{
    var p = _mapper.Map<Product>(updatingProduct);
    var r = await _productService.AddOrUpdateProduct(p);
    return Ok(r);
}
</code>```

ProductService

```<code>public async Task<int?> AddOrUpdateProduct(Product product)
{
   var currentProduct = await _unitOfWork.Repository<Product>().GetByIdAsync(product.Id, t => t.ProductCharacteristics);

   foreach (var item in currentProduct.ProductCharacteristics)
   {
      var exist = product.ProductCharacteristics.ToList().Any(c => c.Id == item.Id);

      if (!exist)
      {
         _unitOfWork.Repository<ProductCharacteristic>().Delete(item);
      }
   }

   _unitOfWork.Repository<Product>().AddOrUpdate(product);

   return await _unitOfWork.Complete();
}
</code>```

GenericRepository

```<code>public async Task<T> GetByIdAsync(int id, params Expression<Func<T, object>>[] includeRelatedTables)
{
   IQueryable<T> x = _context.Set<T>();

   foreach (var item in includeRelatedTables)
   {
      x = x.AsNoTracking().Include(item);
   }

   return await x.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
}

public virtual void Delete(T entity)
{
   _context.Set<T>().Remove(entity);
}

public virtual void AddOrUpdate(T entity)
{
   _context.Set<T>().Update(entity);
}
</code>```

UnitOfWork

```<code>public class UnitOfWork : IUnitOfWork
{
    private readonly ShopDbContext _context;
    private Hashtable _repositories;

    public UnitOfWork(ShopDbContext context)
    {
        _context = context;
    }

    public async Task<int> Complete()
    {
        return await _context.SaveChangesAsync();
    }

    public void Dispose()
    {
        _context.Dispose();
    }

    public IGenericRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
    {
        if (_repositories == null)
           _repositories = new Hashtable();

        var type = typeof(TEntity).Name;

        if (!_repositories.ContainsKey(type))
        {
            var repositoryType = typeof(GenericRepository<>);
            var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context);

            _repositories.Add(type, repositoryInstance);
        }

        return (IGenericRepository<TEntity>)_repositories[type];
    }
}
</code>```

Error:

ERROR  Object { headers: {…}, status: 500, statusText: "Internal
Server Error", url: "https://localhost:6001/api/products/update/7",
ok: false, name: "HttpErrorResponse", message: "Http failure response
for https://localhost:6001/api/products/update/7: 500 Internal Server
Error", error: "System.InvalidOperationException: The instance of
entity type 'Product' cannot be tracked because another instance with
the same key value for {'Id'} is already being tracked. When attaching
existing entities, ensure that only one entity instance with a given
key value is attached. Consider using
'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the
conflicting key values.\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.ThrowIdentityConflict(InternalEntityEntry entry)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey
key, InternalEntityEntry entry, Boolean updateDuplicate)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(InternalEntityEntry
entry)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry
entry)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
oldState, EntityState newState, Boolean acceptChanges, Boolean
modifyProperties)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
entityState, Boolean acceptChanges, Boolean modifyProperties,
Nullable1 forceStateWhenUnknownKey, Nullable1 fallbackState)\r\n

at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode1 node)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode1
node, Func2 handleNode)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)\r\n   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.SetEntityState(InternalEntityEntry
entry, EntityState entityState)\r\n   at
Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Update(TEntity entity)\r\n   at Lili.Shop.DataAccess.Repositories.GenericRepository1.AddOrUpdate(T
entity) in
C:\Workspace\MainProjects\E-Shop\LiliShop-backend-dotnet\Lili.Shop\Main\Applications\Lili.Shop.DataAccess\Repositories\GenericRepository.cs:line
71\r\n   at
Lili.Shop.Service.ProductService.AddOrUpdateProduct(Product product)
in
C:\Workspace\MainProjects\E-Shop\LiliShop-backend-dotnet\Lili.Shop\Main\Applications\Lili.Shop.Service\ProductService.cs:line
74\r\n   at
Lili.Shop.API.Controllers.ProductsController.updateProduct(Int32 id,
ProductToUpdateDto updatingProduct) in
C:\Workspace\MainProjects\E-Shop\LiliShop-backend-dotnet\Lili.Shop\Main\Applications\Lili.Shop.API\Controllers\ProductsController.cs:line
99\r\n   at lambda_method225(Closure, Object)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext
actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor
executor, Object controller, Object[] arguments)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker
invoker, ValueTask`1 actionResultValueTask)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed
context)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker
invoker)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker
invoker)\r\n   at
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger)\r\n   at
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context)\r\n   at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
context)\r\n   at
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext)\r\n   at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider)\r\n   at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext
context)\r\n\r\nHEADERS\r\n=======\r\nAccept: application/json,
text/plain, /\r\nHost: localhost:6001\r\nUser-Agent: Mozilla/5.0
(Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101
Firefox/107.0\r\nAccept-Encoding: gzip, deflate,
br\r\nAccept-Language: en-US,en;q=0.5\r\nAuthorization: Bearer
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InMuci5hbGVtQGdtYWlsLmNvbSIsImdpdmVuX25hbWUiOiJSb29oaSIsInJvbGUiOiJTdXBlckFkbWluIiwibmJmIjoxNjcwNTk4MDk4LCJleHAiOjE2NzEyMDI4OTgsImlhdCI6MTY3MDU5ODA5OCwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NjAwMSJ9.1A9AJmJ52N-hUI1fZqaqfD4X6Y0v51B4z_K3MWQrHDg\r\nContent-Type:
application/json\r\nOrigin: https://localhost:4200\r\nReferer:
https://localhost:4200/\r\nTE: trailers\r\nContent-Length:
549\r\nsec-fetch-dest: empty\r\nsec-fetch-mode:
cors\r\nsec-fetch-site: same-site\r\n" }

Body:
I got this error, when I wanted to update product object:

System.InvalidOperationException: The instance of entity type 'Product' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

How can I  solve it?

ProductsController

[HttpPut("update/{id}")]
public async Task<ActionResult<int>> updateProduct(int id, [FromBody] ProductToUpdateDto updatingProduct)
{
    var p = _mapper.Map<Product>(updatingProduct);
    var r = await _productService.AddOrUpdateProduct(p);
    return Ok(r);
}

ProductService

public async Task<int?> AddOrUpdateProduct(Product product)
{
   var currentProduct = await _unitOfWork.Repository<Product>().GetByIdAsync(product.Id, t => t.ProductCharacteristics);

   foreach (var item in currentProduct.ProductCharacteristics)
   {
      var exist = product.ProductCharacteristics.ToList().Any(c => c.Id == item.Id);

      if (!exist)
      {
         _unitOfWork.Repository<ProductCharacteristic>().Delete(item);
      }
   }

   _unitOfWork.Repository<Product>().AddOrUpdate(product);

   return await _unitOfWork.Complete();
}

GenericRepository

public async Task<T> GetByIdAsync(int id, params Expression<Func<T, object>>[] includeRelatedTables)
{
   IQueryable<T> x = _context.Set<T>();

   foreach (var item in includeRelatedTables)
   {
      x = x.AsNoTracking().Include(item);
   }

   return await x.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
}

public virtual void Delete(T entity)
{
   _context.Set<T>().Remove(entity);
}

public virtual void AddOrUpdate(T entity)
{
   _context.Set<T>().Update(entity);
}

UnitOfWork

public class UnitOfWork : IUnitOfWork
{
    private readonly ShopDbContext _context;
    private Hashtable _repositories;

    public UnitOfWork(ShopDbContext context)
    {
        _context = context;
    }

    public async Task<int> Complete()
    {
        return await _context.SaveChangesAsync();
    }

    public void Dispose()
    {
        _context.Dispose();
    }

    public IGenericRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
    {
        if (_repositories == null)
           _repositories = new Hashtable();

        var type = typeof(TEntity).Name;

        if (!_repositories.ContainsKey(type))
        {
            var repositoryType = typeof(GenericRepository<>);
            var repositoryInstance = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context);

            _repositories.Add(type, repositoryInstance);
        }

        return (IGenericRepository<TEntity>)_repositories[type];
    }
}

Error:

ERROR  Object { headers: {…}, status: 500, statusText: "Internal
Server Error", url: "https://localhost:6001/api/products/update/7",
ok: false, name: "HttpErrorResponse", message: "Http failure response
for https://localhost:6001/api/products/update/7: 500 Internal Server
Error", error: "System.InvalidOperationException: The instance of
entity type 'Product' cannot be tracked because another instance with
the same key value for {'Id'} is already being tracked. When attaching
existing entities, ensure that only one entity instance with a given
key value is attached. Consider using
'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the
conflicting key values.\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.ThrowIdentityConflict(InternalEntityEntry entry)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey
key, InternalEntityEntry entry, Boolean updateDuplicate)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(InternalEntityEntry
entry)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry
entry)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
oldState, EntityState newState, Boolean acceptChanges, Boolean
modifyProperties)\r\n   at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
entityState, Boolean acceptChanges, Boolean modifyProperties,
Nullable1 forceStateWhenUnknownKey, Nullable1 fallbackState)\r\n

at
Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode1 node)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode1
node, Func2 handleNode)\r\n   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)\r\n   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.SetEntityState(InternalEntityEntry
entry, EntityState entityState)\r\n   at
Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.Update(TEntity entity)\r\n   at Lili.Shop.DataAccess.Repositories.GenericRepository1.AddOrUpdate(T
entity) in
C:\Workspace\MainProjects\E-Shop\LiliShop-backend-dotnet\Lili.Shop\Main\Applications\Lili.Shop.DataAccess\Repositories\GenericRepository.cs:line
71\r\n   at
Lili.Shop.Service.ProductService.AddOrUpdateProduct(Product product)
in
C:\Workspace\MainProjects\E-Shop\LiliShop-backend-dotnet\Lili.Shop\Main\Applications\Lili.Shop.Service\ProductService.cs:line
74\r\n   at
Lili.Shop.API.Controllers.ProductsController.updateProduct(Int32 id,
ProductToUpdateDto updatingProduct) in
C:\Workspace\MainProjects\E-Shop\LiliShop-backend-dotnet\Lili.Shop\Main\Applications\Lili.Shop.API\Controllers\ProductsController.cs:line
99\r\n   at lambda_method225(Closure, Object)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext
actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor
executor, Object controller, Object[] arguments)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker
invoker, ValueTask`1 actionResultValueTask)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed
context)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker
invoker)\r\n   at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker
invoker)\r\n   at
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger)\r\n   at
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context)\r\n   at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
context)\r\n   at
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext)\r\n   at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider)\r\n   at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext
context)\r\n\r\nHEADERS\r\n=======\r\nAccept: application/json,
text/plain, /\r\nHost: localhost:6001\r\nUser-Agent: Mozilla/5.0
(Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101
Firefox/107.0\r\nAccept-Encoding: gzip, deflate,
br\r\nAccept-Language: en-US,en;q=0.5\r\nAuthorization: Bearer
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InMuci5hbGVtQGdtYWlsLmNvbSIsImdpdmVuX25hbWUiOiJSb29oaSIsInJvbGUiOiJTdXBlckFkbWluIiwibmJmIjoxNjcwNTk4MDk4LCJleHAiOjE2NzEyMDI4OTgsImlhdCI6MTY3MDU5ODA5OCwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NjAwMSJ9.1A9AJmJ52N-hUI1fZqaqfD4X6Y0v51B4z_K3MWQrHDg\r\nContent-Type:
application/json\r\nOrigin: https://localhost:4200\r\nReferer:
https://localhost:4200/\r\nTE: trailers\r\nContent-Length:
549\r\nsec-fetch-dest: empty\r\nsec-fetch-mode:
cors\r\nsec-fetch-site: same-site\r\n" }


问:
Pros and cons of binary representation in a genetic algorithm
I'm solving problem of making teams of players for some game, using genetic algorithm.

Having pool of players to split, I represent individual from population as a row of teams, where each team is some list or an array of number of players in pool. I translate each number to the binary encode, as if it was in "original" genetic algo. But now I start to think of advantages and disadvantages of binary representation of the individuals.

My thoughts were that I can use very common mutation and crossover frameworks: just change bits and change tails, accordingly. But I am able to do it with just integer numbers, simply using some manual mutation function.

So, the question is: what are the benefits and drawbacks of the binary/integer-valued representation? What is most "true" way to use GA?

I checked original book by author of GA, John Holland, and there he uses binary representation, but I haven't found (yet probably) information about what representation fits best.

In this answer shown one drawback whilst using float numbers: after crossover two parents could move far away from each other. But in my case I don't need to use float numbers.


问:
Column widths are broken for non-latin characters in console
I have this rather inconvenient problem with mysql console client, the column widths in display are broken for non-latin characters, i.e. mysql makes the column 1.5 times wider than it needs to be for Chinese characters, Cyrillic is even worse, the column is twice as wide as it needs to be, i.e. for a string 100 characters wide, the column width will be 200 characters which makes the output absolute mess really. Is there a way to fix this? I tried to use -r -s and \P but I could not get anything suitable.

See the example below, note how abc column is exactly as wide as the string RRRRRRR plus two margin characters, and how zh and cyr are incorrectly padded as if the input contained invisible spaces.

```<code> select '你好你好' as zh, 'RRRRRRR' as abc, 'ЯЯЯЯЯЯЯ' as cyr;
+--------------+---------+----------------+
| zh           | abc     | cyr            |
+--------------+---------+----------------+
| 你好你好     | RRRRRRR | ЯЯЯЯЯЯЯ        |
+--------------+---------+----------------+
</code>```

Body:
I have this rather inconvenient problem with mysql console client, the column widths in display are broken for non-latin characters, i.e. mysql makes the column 1.5 times wider than it needs to be for Chinese characters, Cyrillic is even worse, the column is twice as wide as it needs to be, i.e. for a string 100 characters wide, the column width will be 200 characters which makes the output absolute mess really. Is there a way to fix this? I tried to use -r -s and \P but I could not get anything suitable.

See the example below, note how abc column is exactly as wide as the string RRRRRRR plus two margin characters, and how zh and cyr are incorrectly padded as if the input contained invisible spaces.

 select '你好你好' as zh, 'RRRRRRR' as abc, 'ЯЯЯЯЯЯЯ' as cyr;
+--------------+---------+----------------+
| zh           | abc     | cyr            |
+--------------+---------+----------------+
| 你好你好     | RRRRRRR | ЯЯЯЯЯЯЯ        |
+--------------+---------+----------------+


问:
How to search meal by name using Mealdb API for Python
In my objects.py I have this code for meals:

```<code>class Meal:
    def __init__(self, meal_id, meal_name, meal_thumb):
        self.__meal_id = meal_id
        self.__meal_name = meal_name
        self.__meal_thumb = meal_thumb

    def get_meal_id(self):
        return self.__meal_id

    def set_meal_id(self, meal_id):
        self.__meal_id = meal_id

    def get_name(self):
        return self.__meal_name

    def set_name(self, meal_name):
        self.__meal_name = meal_name

    def get_meal_thumb(self):
        return self.__meal_thumb

    def set_meal_thumb(self, meal_thumb):
        self.__meal_thumb = meal_thumb
</code>```

In my requests.py I came up with:

```<code>def get_all_meals():
    url = "https://www.themealdb.com/api/json/v1/1/search.php?f=a"
    f = request.urlopen(url)
    all_meals = []

    try:
        data = json.loads(f.read().decode('utf-8'))
        for meal_data in data['meals']:
            meal = Meal(meal_data['strMeal'],
                        meal_data['strMeal'],
                        meal_data['strMealThumb'])

            all_meals.append(meal)
    except(ValueError, KeyError, TypeError):
        return None

    return all_meals

def get_meal_by_name(meal):
    url = "https://www.themealdb.com/api/json/v1/1/search.php?s=" + parse.quote(meal)
    f = request.urlopen(url)

    try:
        data = json.loads(f.read().decode('utf-8'))
        for meal_data in data['meals']:
            meal = Meal(meal_data['idMeal'],
                        meal_data['strMeal'],
                        meal_data['strMealThumb'])
    except(ValueError, KeyError, TypeError):
        return None

    return meal
</code>```

I'm not sure if need get_all_meals() or just get_meal_by_name(meal).
In my recipes.py I have:

```<code>def list_meal_by_name():
    lookup_meal = input("Enter Meal Name: ")

    all_meals = requests.get_all_meals()
    found = False

    if all_meals is None:
        print("Technical difficulties, please try again later.")
    else:
        for i in range(len(all_meals)):
            meal = all_meals[i]
            if meal.get_meal_id().lower() == lookup_meal.lower():
                found = True
                break

        if found:
            meal = lookup_meal
            recipe = requests.get_meal_by_name(meal)
            my_wrap = textwrap.TextWrapper(width=80)
            wrap_list = my_wrap.wrap("Instructions: " + recipe.get_instructions())
            for line in wrap_list:
                print(line)
        else:
            print("Invalid meal name. Please try again.")
            print()
</code>```

I was trying to run the user input through the list of all meals in the Mealdb API. If that was found I wanted the meal and instructions to print, but it jumps to the else statement and prints "Invalid meal name. Please try again." I'm not sure what to code in the if statement to make it run and print properly. Also, the "recipe.get_instructions()" is a hint given for this project so I'm not sure what I need to do to make it work.

Body:
In my objects.py I have this code for meals:

class Meal:
    def __init__(self, meal_id, meal_name, meal_thumb):
        self.__meal_id = meal_id
        self.__meal_name = meal_name
        self.__meal_thumb = meal_thumb

    def get_meal_id(self):
        return self.__meal_id

    def set_meal_id(self, meal_id):
        self.__meal_id = meal_id

    def get_name(self):
        return self.__meal_name

    def set_name(self, meal_name):
        self.__meal_name = meal_name

    def get_meal_thumb(self):
        return self.__meal_thumb

    def set_meal_thumb(self, meal_thumb):
        self.__meal_thumb = meal_thumb

In my requests.py I came up with:

def get_all_meals():
    url = "https://www.themealdb.com/api/json/v1/1/search.php?f=a"
    f = request.urlopen(url)
    all_meals = []

    try:
        data = json.loads(f.read().decode('utf-8'))
        for meal_data in data['meals']:
            meal = Meal(meal_data['strMeal'],
                        meal_data['strMeal'],
                        meal_data['strMealThumb'])

            all_meals.append(meal)
    except(ValueError, KeyError, TypeError):
        return None

    return all_meals

def get_meal_by_name(meal):
    url = "https://www.themealdb.com/api/json/v1/1/search.php?s=" + parse.quote(meal)
    f = request.urlopen(url)

    try:
        data = json.loads(f.read().decode('utf-8'))
        for meal_data in data['meals']:
            meal = Meal(meal_data['idMeal'],
                        meal_data['strMeal'],
                        meal_data['strMealThumb'])
    except(ValueError, KeyError, TypeError):
        return None

    return meal

I'm not sure if need get_all_meals() or just get_meal_by_name(meal).
In my recipes.py I have:

def list_meal_by_name():
    lookup_meal = input("Enter Meal Name: ")

    all_meals = requests.get_all_meals()
    found = False

    if all_meals is None:
        print("Technical difficulties, please try again later.")
    else:
        for i in range(len(all_meals)):
            meal = all_meals[i]
            if meal.get_meal_id().lower() == lookup_meal.lower():
                found = True
                break

        if found:
            meal = lookup_meal
            recipe = requests.get_meal_by_name(meal)
            my_wrap = textwrap.TextWrapper(width=80)
            wrap_list = my_wrap.wrap("Instructions: " + recipe.get_instructions())
            for line in wrap_list:
                print(line)
        else:
            print("Invalid meal name. Please try again.")
            print()

I was trying to run the user input through the list of all meals in the Mealdb API. If that was found I wanted the meal and instructions to print, but it jumps to the else statement and prints "Invalid meal name. Please try again." I'm not sure what to code in the if statement to make it run and print properly. Also, the "recipe.get_instructions()" is a hint given for this project so I'm not sure what I need to do to make it work.


问:
dynamic css grid | height doesn't apply to second row
I want to create a dynamic grid.

this is my current css. What am i missing that the row hight is not applied to the second row?

```<code>.container{
    display: grid;
    grid-template-columns: repeat(auto-fill, 170px);
    grid-template-rows: repeat(auto-fill, 300px);
}
</code>```

html:

```<code><div class="container">
   <div>
       css
   </div>
   <div>
      html
   </div>
</div>

</code>```

Body:
I want to create a dynamic grid.

this is my current css. What am i missing that the row hight is not applied to the second row?

.container{
    display: grid;
    grid-template-columns: repeat(auto-fill, 170px);
    grid-template-rows: repeat(auto-fill, 300px);
}

html:

       css

      html


问:
Aforge PictureBox throws "System.InvalidOperationException: 'The object is currently in use elsewhere.'"
Aforge PictureBox throws "System.InvalidOperationException: 'The object is currently in use elsewhere.'" when I resize or move the application window.
In some situations it throws an Exception that indicates the use in several threads.

Exception

Main Code:

```<code>    public partial class MainForm : Form
    {

    //Global Var

        String[] serialLog = new String[300];
        SerialLogDisplay sld_form;

        FilterInfoCollection filterInfoCollection;
        VideoCaptureDevice videoCaptureDevice;

        //Form Method

        public MainForm()
        {
            InitializeComponent();
        }

    //Generated Methods

        private void btnCCamera_Click(object sender, EventArgs e)
        {
            if(cmbCameraS.SelectedIndex > 0) {
                disconnectVideoStream(false);
                videoCaptureDevice = new VideoCaptureDevice(filterInfoCollection[cmbCameraS.SelectedIndex-1].MonikerString);
                videoCaptureDevice.NewFrame += VideoCaptureDevice_NewFrame;
                videoCaptureDevice.Start();

                Add_Log("Camera \"" + filterInfoCollection[cmbCameraS.SelectedIndex-1].Name+ "\" Connected!");
            }
            else
            {
                disconnectVideoStream(true);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Camera System
            cmbCameraS.Items.Add("None");
            filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo filterInfo in filterInfoCollection)
            {
                cmbCameraS.Items.Add(filterInfo.Name);
            }
            cmbCameraS.SelectedIndex = 0;
            videoCaptureDevice = new VideoCaptureDevice();

            //Log
            shortLog.Parent = cameraDisplay;
            shortLog.BackColor = Color.Transparent;
            shortLog.Text = serialLog[0] + "\n" + serialLog[1] + "\n" + serialLog[2];

            //Loop
            Timer tmr = new Timer();
            tmr.Interval = 1000;
            tmr.Tick += Tmr_Tick;
            tmr.Start();

            //DisplayObjects
            MPpanel.Parent = cameraDisplay;

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            disconnectVideoStream(false);
        }

        private void SLbtn_Click(object sender, EventArgs e)
        {
            if (sld_form == null)
            {
                sld_form = new SerialLogDisplay(this);
            }
            sld_form.update_log(serialLog);
            sld_form.Show();
            sld_form.Activate();
        }

        //Created Methods

        //Serial Log
        private void Tmr_Tick(object sender, EventArgs e)
        {
            String lm = "";
            for (int i = 4; i >= 0; i--)
            {
                if (serialLog[i] != null)
                {
                    lm += serialLog[i] + "\n";
                }
            }
            shortLog.Text = lm;
        }

        public void SerialLogDisplay_Close()
        {
            sld_form = null;
        }

        public void Add_Log(String text)
        {
            for (int i = serialLog.Length - 1; i > 0; i--)
            {
                serialLog[i] = serialLog[i - 1];
            }
            serialLog[0] = text;

            if(sld_form != null)
            {
                sld_form.update_log(serialLog);
            }

        }

        public void Serial_Command(String command)
        {
            Add_Log(command);
            //Send command to serial Port
        }

        //Camera Output
        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                if (cameraDisplay.Image != null)
                {
                    cameraDisplay.Image.Dispose();
                }
                Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
                cameraDisplay.Image = bmp;
            }
            catch (System.InvalidOperationException ex)
            {
                Add_Log("Error: " + ex);
                disconnectVideoStream(true);
            }

            //GC.Collect();
        }

        private void disconnectVideoStream(bool showLog)
        {
            if (videoCaptureDevice.IsRunning == true)
            {
                if (showLog) { Add_Log("Disconnecting video stream..."); }
                videoCaptureDevice.SignalToStop();
                videoCaptureDevice.WaitForStop();
                videoCaptureDevice.Stop();
                cameraDisplay.Image = null;
            }

            if (showLog)
            {
                Add_Log("No camera connected!");
            }
            GC.Collect();
        }
    }
</code>```

"CameraDysplay" -> PictureBox

I tried to put the Bitmap image as global, but it didn't work...
I also tried blocking the application window size change, but the error remains...

I tried to use invoke and it worked, but it crashes when closing the application.

```<code>        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Invoke(new Action(() => {
                try
                {
                    if (cameraDisplay.Image != null)
                    {
                        cameraDisplay.Image.Dispose();
                    }
                    Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
                    cameraDisplay.Image = bmp;
                }
                catch (System.InvalidOperationException ex)
                {
                    Add_Log("Error: " + ex);
                    disconnectVideoStream(true);
                }
            }));
            //GC.Collect();
        }
</code>```

Body:
Aforge PictureBox throws "System.InvalidOperationException: 'The object is currently in use elsewhere.'" when I resize or move the application window.
In some situations it throws an Exception that indicates the use in several threads.

Exception

Main Code:

    public partial class MainForm : Form
    {

    //Global Var

        String[] serialLog = new String[300];
        SerialLogDisplay sld_form;

        FilterInfoCollection filterInfoCollection;
        VideoCaptureDevice videoCaptureDevice;

        //Form Method

        public MainForm()
        {
            InitializeComponent();
        }

    //Generated Methods

        private void btnCCamera_Click(object sender, EventArgs e)
        {
            if(cmbCameraS.SelectedIndex > 0) {
                disconnectVideoStream(false);
                videoCaptureDevice = new VideoCaptureDevice(filterInfoCollection[cmbCameraS.SelectedIndex-1].MonikerString);
                videoCaptureDevice.NewFrame += VideoCaptureDevice_NewFrame;
                videoCaptureDevice.Start();

                Add_Log("Camera \"" + filterInfoCollection[cmbCameraS.SelectedIndex-1].Name+ "\" Connected!");
            }
            else
            {
                disconnectVideoStream(true);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Camera System
            cmbCameraS.Items.Add("None");
            filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo filterInfo in filterInfoCollection)
            {
                cmbCameraS.Items.Add(filterInfo.Name);
            }
            cmbCameraS.SelectedIndex = 0;
            videoCaptureDevice = new VideoCaptureDevice();

            //Log
            shortLog.Parent = cameraDisplay;
            shortLog.BackColor = Color.Transparent;
            shortLog.Text = serialLog[0] + "\n" + serialLog[1] + "\n" + serialLog[2];

            //Loop
            Timer tmr = new Timer();
            tmr.Interval = 1000;
            tmr.Tick += Tmr_Tick;
            tmr.Start();

            //DisplayObjects
            MPpanel.Parent = cameraDisplay;

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            disconnectVideoStream(false);
        }

        private void SLbtn_Click(object sender, EventArgs e)
        {
            if (sld_form == null)
            {
                sld_form = new SerialLogDisplay(this);
            }
            sld_form.update_log(serialLog);
            sld_form.Show();
            sld_form.Activate();
        }

        //Created Methods

        //Serial Log
        private void Tmr_Tick(object sender, EventArgs e)
        {
            String lm = "";
            for (int i = 4; i >= 0; i--)
            {
                if (serialLog[i] != null)
                {
                    lm += serialLog[i] + "\n";
                }
            }
            shortLog.Text = lm;
        }

        public void SerialLogDisplay_Close()
        {
            sld_form = null;
        }

        public void Add_Log(String text)
        {
            for (int i = serialLog.Length - 1; i > 0; i--)
            {
                serialLog[i] = serialLog[i - 1];
            }
            serialLog[0] = text;

            if(sld_form != null)
            {
                sld_form.update_log(serialLog);
            }

        }

        public void Serial_Command(String command)
        {
            Add_Log(command);
            //Send command to serial Port
        }

        //Camera Output
        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                if (cameraDisplay.Image != null)
                {
                    cameraDisplay.Image.Dispose();
                }
                Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
                cameraDisplay.Image = bmp;
            }
            catch (System.InvalidOperationException ex)
            {
                Add_Log("Error: " + ex);
                disconnectVideoStream(true);
            }

            //GC.Collect();
        }

        private void disconnectVideoStream(bool showLog)
        {
            if (videoCaptureDevice.IsRunning == true)
            {
                if (showLog) { Add_Log("Disconnecting video stream..."); }
                videoCaptureDevice.SignalToStop();
                videoCaptureDevice.WaitForStop();
                videoCaptureDevice.Stop();
                cameraDisplay.Image = null;
            }

            if (showLog)
            {
                Add_Log("No camera connected!");
            }
            GC.Collect();
        }
    }

"CameraDysplay" -> PictureBox

I tried to put the Bitmap image as global, but it didn't work...
I also tried blocking the application window size change, but the error remains...

I tried to use invoke and it worked, but it crashes when closing the application.

        private void VideoCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Invoke(new Action(() => {
                try
                {
                    if (cameraDisplay.Image != null)
                    {
                        cameraDisplay.Image.Dispose();
                    }
                    Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
                    cameraDisplay.Image = bmp;
                }
                catch (System.InvalidOperationException ex)
                {
                    Add_Log("Error: " + ex);
                    disconnectVideoStream(true);
                }
            }));
            //GC.Collect();
        }


问:
React Three Fiber, Three.js and Drei: lazy import models using components gets re-rendered to infinity
I'm trying to lazy import JSX models in React Three Fiber.
I have a couple of JSX models which incorporate useGLTF() from drei, to load the actual .gltf/.glb model, as nodes and materials, like in the R3F tutorial.

What I'm trying to do now, is to lazy import those JSX model components on demand, through my ModelsLoader component.

The problem is that even when I use memo() or useMemo() from React, the component gets re-rendered constantly...

I don't know what I'm doing wrong, or even if what I'm trying to do is even possible, but hey, there are a lot of smart people here, some maybe you'll be able to help me ;)

example of my JSX model component, which I'm trying to lazy import in ModelsLoader component:

```<code>import React, { useRef } from 'react';
import { useGLTF } from '@react-three/drei';

export default function OCF155(props) {
  const { nodes } = useGLTF('models/EXAMPLE_MODEL.glb');
  const ref = useRef();
  return (
    <group {...props} ref={ref} dispose={null} type='TopParent'>
      <mesh
        name='EXAMPLE_MODEL'
        castShadow
        receiveShadow
        geometry={nodes.EXAMPLE_MODEL.geometry}
        material={nodes.EXAMPLE_MODEL.material}
        rotation={[Math.PI / 2, 0, 0]}
        scale={1}
      />
    </group>
  );
}
</code>```

And here is my ModelsLoader component as it's stands for now, using .memo():

```<code>import React, { memo, lazy } from 'react';
import Selection from './helpers/Selection';

const ModelsLoader = memo(function ModelsLoader({ models }) {
  return (
    <>
      {models &&
        models.length > 0 &&
        models.map((model, index) => {
          const ModelComponent = lazy(() => import(`./models/${model.name}`));
          return (
            <Selection key={index}>
              <ModelComponent
                position={model.position}
                rotation={model.rotation}
              />
            </Selection>
          );
        })}
    </>
  );
});

export default ModelsLoader;
</code>```

I was trying to do it without .memo(), but the result was the same. I was thinking, that if I use .memo(), hence the models list is not changing throughout the render of the page, it will get rendered once and then passed on...

Body:
I'm trying to lazy import JSX models in React Three Fiber.
I have a couple of JSX models which incorporate useGLTF() from drei, to load the actual .gltf/.glb model, as nodes and materials, like in the R3F tutorial.

What I'm trying to do now, is to lazy import those JSX model components on demand, through my ModelsLoader component.

The problem is that even when I use memo() or useMemo() from React, the component gets re-rendered constantly...

I don't know what I'm doing wrong, or even if what I'm trying to do is even possible, but hey, there are a lot of smart people here, some maybe you'll be able to help me ;)

example of my JSX model component, which I'm trying to lazy import in ModelsLoader component:

import React, { useRef } from 'react';
import { useGLTF } from '@react-three/drei';

export default function OCF155(props) {
  const { nodes } = useGLTF('models/EXAMPLE_MODEL.glb');
  const ref = useRef();
  return (
    <group {...props} ref={ref} dispose={null} type='TopParent'>
      <mesh
        name='EXAMPLE_MODEL'
        castShadow
        receiveShadow
        geometry={nodes.EXAMPLE_MODEL.geometry}
        material={nodes.EXAMPLE_MODEL.material}
        rotation={[Math.PI / 2, 0, 0]}
        scale={1}
      />
    </group>
  );
}

And here is my ModelsLoader component as it's stands for now, using .memo():

import React, { memo, lazy } from 'react';
import Selection from './helpers/Selection';

const ModelsLoader = memo(function ModelsLoader({ models }) {
  return (
    <>
      {models &&
        models.length > 0 &&
        models.map((model, index) => {
          const ModelComponent = lazy(() => import(`./models/${model.name}`));
          return (
            <Selection key={index}>
              <ModelComponent
                position={model.position}
                rotation={model.rotation}
              />
            </Selection>
          );
        })}
    </>
  );
});

export default ModelsLoader;

I was trying to do it without .memo(), but the result was the same. I was thinking, that if I use .memo(), hence the models list is not changing throughout the render of the page, it will get rendered once and then passed on...


问:
POST request error 403 Microsoft graph from Excel VBA
I am trying to create folder on sharepoint site with Microsoft graph from Excel VBA, code working on some endpoints but on some it return response error 403. On App permission side, everything looks fine and all permissions are granted. Please look at code below:</p>
```<code>Sub create_folder()

Dim http As New MSXML2.XMLHTTP60
  Dim url As String

        access_token = "tokentokentoken"
        url = "https://graph.microsoft.com/v1.0/drives/{drive-id}/items/"
        http.Open "POST", url, False
        http.setRequestHeader "application", "x-www-form-urlencoded"
        http.setRequestHeader "Content-Type", "application/json;odata=verbose"
        http.setRequestHeader "Authorization", "Bearer " & access_token
        http.send "{""name"": ""New Folder"", ""folder"": {}}"

        If http.Status = 200 Then
            MsgBox ("OK")
        End If
        Set XMLHTTP = Nothing

End Sub
</code>```

Body:
I am trying to create folder on sharepoint site with Microsoft graph from Excel VBA, code working on some endpoints but on some it return response error 403. On App permission side, everything looks fine and all permissions are granted. Please look at code below:

Sub create_folder()

Dim http As New MSXML2.XMLHTTP60
  Dim url As String

        access_token = "tokentokentoken"
        url = "https://graph.microsoft.com/v1.0/drives/{drive-id}/items/"
        http.Open "POST", url, False
        http.setRequestHeader "application", "x-www-form-urlencoded"
        http.setRequestHeader "Content-Type", "application/json;odata=verbose"
        http.setRequestHeader "Authorization", "Bearer " & access_token
        http.send "{""name"": ""New Folder"", ""folder"": {}}"

        If http.Status = 200 Then
            MsgBox ("OK")
        End If
        Set XMLHTTP = Nothing

End Sub


问:
Use typing.List or list in a python type hint?
https://docs.python.org/3/library/typing.html has the following example for aliasing:

```<code>Vector = list[float]
</code>```

So, you can use list as a list in a type hint (or at least an alias).

However, the typing module also has a List.

If I'm defining a function arg type hint, should I use list or List?

```<code>def list_len(a_list: list):
    return len(a_list)
</code>```

or

```<code>def list_len(a_list: List):
    return len(a_list)
</code>```

?

There are other possibilities too (e.g., Sequence).  My first question is just list or List.  My second is, is there somewhere that describes a best practice in this situation?  (For example, use Sequence, or Iterable, or ..)

Body:
https://docs.python.org/3/library/typing.html has the following example for aliasing:

Vector = list[float]

So, you can use list as a list in a type hint (or at least an alias).

However, the typing module also has a List.

If I'm defining a function arg type hint, should I use list or List?

def list_len(a_list: list):
    return len(a_list)

or

def list_len(a_list: List):
    return len(a_list)

?

There are other possibilities too (e.g., Sequence).  My first question is just list or List.  My second is, is there somewhere that describes a best practice in this situation?  (For example, use Sequence, or Iterable, or ..)


问:
MVC Using partials to post editable view models that are multiple levels deep
It appears that list data is only posted to the controller if it is "hidden" using the full model path.  Partials don't seem to work unless they are passed the entire view model starting at the top.

In my example, PageVM has a list of TeamVM's which have a list of BatterVM's.  The only way I could get a successful post result is to:

The view's @model must specify the top most object in the view model (PageVM in this example)

Model references must include the full model; i.e. this has the PageVM, TeamVM, and BatterVM
@Html.HiddenFor(model => model.TeamVMs[t].BatterVMs[b].BatterID)

When viewing source, this would result in a fully qualified statement:

```<code><input data-val="true" data-val-required="The BatterID field is required." id="**TeamVMs_0__BatterVMs_0__BatterID**" name="TeamVMs[0].BatterVMs[0].BatterID" type="hidden" value="10" />
</code>```

When I tried using partials and passed in a lower level model, i.e. @using TeamVM instead of PageVM, the id was no longer fully qualified and would return null upon submit

Am I overlooking an option to use partials?

Controller

```<code>        public IActionResult Loops()
        {
            PageVM pageVM = GetSample();
            return View(pageVM);
        }

</code>```
```<code>        private PageVM GetSample ()
        {
            //               Page
            // 5 Yankees            6 Reds              TEAMS
            //-----------------     ------------------
            // 10 Babe Ruth         50 Johnny Bench     PLAYERS
            // 20 Mickey Mantle     60 Pete Rose

            PageVM pageVM = new PageVM();
            pageVM.LeagueID = 1;
            pageVM.Name = "Best Teams";

            List<TeamVM> teamVMs = new List<TeamVM>
            {
                new TeamVM { TeamID = 5, Name = "Yankees" },
                new TeamVM { TeamID = 6, Name = "Reds" }
            };

            List<BatterVM> batterVMs1 = new List<BatterVM>
            {
                new BatterVM { BatterID = 10, Name = "Babe Ruth" },
                new BatterVM { BatterID = 20, Name = "Mickey Mantle" }
            };

            List<BatterVM> batterVMs2 = new List<BatterVM>
            {
                new BatterVM { BatterID = 50, Name = "Johnny Bench" },
                new BatterVM { BatterID = 60, Name = "Pete Rose" }
            };

            teamVMs[0].BatterVMs = new List<BatterVM>();
            teamVMs[1].BatterVMs = new List<BatterVM>();

            teamVMs[0].BatterVMs.AddRange(batterVMs1);
            teamVMs[1].BatterVMs.AddRange(batterVMs2);

            pageVM.TeamVMs = new List<TeamVM>();

            pageVM.TeamVMs.AddRange(teamVMs);

            return pageVM;
        }
    }
</code>```

Loops.cshtml - this works as expected

```<code>@model BB.Web.Controllers.PageVM;

@using (Html.BeginForm("Loops", "Test", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <input id="btnSubmit" name="submit" type="submit" value="Submit" style="padding:5px 5px 5px 5px; background-color:blueviolet; color:white;" />
    <br />
    @*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@
    @Html.HiddenFor(model => model.LeagueID)
    @Html.HiddenFor(model => model.Name)

    @Html.DisplayFor(model => model.Name) <br />

    @for (int t = 0; t < 2; t++)
    {
        @Html.HiddenFor(model => model.TeamVMs[t].TeamID)
        @Html.HiddenFor(model => model.TeamVMs[t].Name)

        @Html.DisplayFor(model => model.TeamVMs[t].TeamID)
        @Html.DisplayFor(model => model.TeamVMs[t].Name) <br />

        @for(int b = 0; b < 2; b++)
        {
            @Html.HiddenFor(model => model.TeamVMs[t].BatterVMs[b].BatterID)
            @Html.DisplayFor(model => model.TeamVMs[t].BatterVMs[b].BatterID) @Html.DisplayFor(model => model.TeamVMs[t].BatterVMs[b].Name)
            <br />
        }

    }

}
</code>```

Partials - I have to pass in the entire Model to fully qualify and would like to just pass in the Team.

```<code>@using BB.Shared.HtmlHelpers;
@model BB.Web.Controllers.PageVM;

@using (Html.BeginForm("Loops", "Test", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <input id="btnSubmit" name="submit" type="submit" value="Submit" style="padding:5px 5px 5px 5px; background-color:blueviolet; color:white;" />
    <br />
    @*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@
    @Html.HiddenFor(model => model.LeagueID)
    @Html.HiddenFor(model => model.Name)

    @Html.DisplayFor(model => model.Name) <br />

    @Html.Partial("_Partial_Team", **Model**)

}
</code>```

Body:
It appears that list data is only posted to the controller if it is "hidden" using the full model path.  Partials don't seem to work unless they are passed the entire view model starting at the top.

In my example, PageVM has a list of TeamVM's which have a list of BatterVM's.  The only way I could get a successful post result is to:

The view's @model must specify the top most object in the view model (PageVM in this example)

Model references must include the full model; i.e. this has the PageVM, TeamVM, and BatterVM
@Html.HiddenFor(model => model.TeamVMs[t].BatterVMs[b].BatterID)

When viewing source, this would result in a fully qualified statement:

<input data-val="true" data-val-required="The BatterID field is required." id="**TeamVMs_0__BatterVMs_0__BatterID**" name="TeamVMs[0].BatterVMs[0].BatterID" type="hidden" value="10" />

When I tried using partials and passed in a lower level model, i.e. @using TeamVM instead of PageVM, the id was no longer fully qualified and would return null upon submit

Am I overlooking an option to use partials?

Controller

        public IActionResult Loops()
        {
            PageVM pageVM = GetSample();
            return View(pageVM);
        }

        private PageVM GetSample ()
        {
            //               Page
            // 5 Yankees            6 Reds              TEAMS
            //-----------------     ------------------
            // 10 Babe Ruth         50 Johnny Bench     PLAYERS
            // 20 Mickey Mantle     60 Pete Rose

            PageVM pageVM = new PageVM();
            pageVM.LeagueID = 1;
            pageVM.Name = "Best Teams";

            List<TeamVM> teamVMs = new List<TeamVM>
            {
                new TeamVM { TeamID = 5, Name = "Yankees" },
                new TeamVM { TeamID = 6, Name = "Reds" }
            };

            List<BatterVM> batterVMs1 = new List<BatterVM>
            {
                new BatterVM { BatterID = 10, Name = "Babe Ruth" },
                new BatterVM { BatterID = 20, Name = "Mickey Mantle" }
            };

            List<BatterVM> batterVMs2 = new List<BatterVM>
            {
                new BatterVM { BatterID = 50, Name = "Johnny Bench" },
                new BatterVM { BatterID = 60, Name = "Pete Rose" }
            };

            teamVMs[0].BatterVMs = new List<BatterVM>();
            teamVMs[1].BatterVMs = new List<BatterVM>();

            teamVMs[0].BatterVMs.AddRange(batterVMs1);
            teamVMs[1].BatterVMs.AddRange(batterVMs2);

            pageVM.TeamVMs = new List<TeamVM>();

            pageVM.TeamVMs.AddRange(teamVMs);

            return pageVM;
        }
    }

Loops.cshtml - this works as expected

@model BB.Web.Controllers.PageVM;

@using (Html.BeginForm("Loops", "Test", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <input id="btnSubmit" name="submit" type="submit" value="Submit" style="padding:5px 5px 5px 5px; background-color:blueviolet; color:white;" />

    @*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@
    @Html.HiddenFor(model => model.LeagueID)
    @Html.HiddenFor(model => model.Name)

    @Html.DisplayFor(model => model.Name)

    @for (int t = 0; t < 2; t++)
    {
        @Html.HiddenFor(model => model.TeamVMs[t].TeamID)
        @Html.HiddenFor(model => model.TeamVMs[t].Name)

        @Html.DisplayFor(model => model.TeamVMs[t].TeamID)
        @Html.DisplayFor(model => model.TeamVMs[t].Name)

        @for(int b = 0; b < 2; b++)
        {
            @Html.HiddenFor(model => model.TeamVMs[t].BatterVMs[b].BatterID)
            @Html.DisplayFor(model => model.TeamVMs[t].BatterVMs[b].BatterID) @Html.DisplayFor(model => model.TeamVMs[t].BatterVMs[b].Name)

        }

    }

}

Partials - I have to pass in the entire Model to fully qualify and would like to just pass in the Team.

@using BB.Shared.HtmlHelpers;
@model BB.Web.Controllers.PageVM;

@using (Html.BeginForm("Loops", "Test", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <input id="btnSubmit" name="submit" type="submit" value="Submit" style="padding:5px 5px 5px 5px; background-color:blueviolet; color:white;" />

    @*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@
    @Html.HiddenFor(model => model.LeagueID)
    @Html.HiddenFor(model => model.Name)

    @Html.DisplayFor(model => model.Name)

    @Html.Partial("_Partial_Team", **Model**)

}


问:
slot[trigger] should have exactly one child
I am learning vue/naive ui and am trying to get a popover on a button with an icon. However, clicking on that button produces this error in the console:

```<code>slot[trigger] should have exactly one child
</code>```

Here is the popover with the button:

```<code>NPopover(trigger="hover" placement="top")
    template(#trigger="")
      NButton(ref="fullScreenButton" type="primary" strong size="small" @click="toggleFullScreenButton" v-if="!isFullScreen" :size="iconSize")
        NIcon(:size="iconSize")
          FullscreenSharp
    | Full Screen
</code>```

Why do slots only allow one child? How can I fix this?

Body:
I am learning vue/naive ui and am trying to get a popover on a button with an icon. However, clicking on that button produces this error in the console:

slot[trigger] should have exactly one child

Here is the popover with the button:

NPopover(trigger="hover" placement="top")
    template(#trigger="")
      NButton(ref="fullScreenButton" type="primary" strong size="small" @click="toggleFullScreenButton" v-if="!isFullScreen" :size="iconSize")
        NIcon(:size="iconSize")
          FullscreenSharp
    | Full Screen

Why do slots only allow one child? How can I fix this?