问:
C++ function pointer works but std::function not
I'm going to make a benchmark function, which measures the elapsed time of given function execution and returns execution result and elapsed time.

template <typename TResult>
struct BenchmarkResult{
    TResult result;
    const long elapsed;
};

template <typename Ratio, typename TResult, typename... TParams>
BenchmarkResult<TResult> benchmark(TResult (*function)(TParams...), TParams ...params){
    using namespace std::chrono;

    const auto begin = high_resolution_clock::now();
    auto result = function(std::forward<TParams>(params)...);
    const auto end = high_resolution_clock::now();

    return { std::move(result), duration_cast<Ratio>(end - begin).count() };
}
```
<p>And for example,</p>
<pre class="lang-cpp prettyprint-override"><code>int sleep(int seconds){
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(1s);

    return seconds * 1e6; // return the given second in microsecond unit
}

// (implement above code)

int main(){
    auto [elapsed_us, elapsed_ms] = benchmark<std::chrono::milliseconds>(sleep, 1);
    std::cout << "Elapsed ms: " << elapsed_ms << " Elapsed us: " << elapsed_us;;

    return 0;
}
</code>```

Will output like

Elapsed ms: 1005 Elapsed us: 1000000

My goal is to change the argument type like BenchmarkResult<TResult> benchmark(std::function<TResult(TParams...)> function, TParams ...params). But it does not works for the above example in the latest C++ version.

The compiler says,

```<code>/main.cpp: In function 'int main()':
/main.cpp:76:73: error: no matching function for call to 'benchmark<std::chrono::milliseconds>(int (&)(int), int)'
   76 |     auto [elapsed_us, elapsed_ms] = benchmark<std::chrono::milliseconds>(sleep, 1);
      |                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~
/main.cpp:54:26: note: candidate: 'template<class Ratio, class TResult, class ... TParams> BenchmarkResult<TResult> benchmark(std::function<TResult(TParams ...)>, TParams ...)'
   54 | BenchmarkResult<TResult> benchmark(std::function<TResult(TParams...)> function, TParams ...params){ // TODO: use std::function instead of function pointer
      |                          ^~~~~~~~~
/main.cpp:54:26: note:   template argument deduction/substitution failed:
/main.cpp:76:73: note:   mismatched types 'std::function<TResult(TParams ...)>' and 'int (*)(int)'
   76 |     auto [elapsed_us, elapsed_ms] = benchmark<std::chrono::milliseconds>(sleep, 1);
</code>```

How can I achieve this?

Body:
I'm going to make a benchmark function, which measures the elapsed time of given function execution and returns execution result and elapsed time.

template <typename TResult>
struct BenchmarkResult{
    TResult result;
    const long elapsed;
};

template <typename Ratio, typename TResult, typename... TParams>
BenchmarkResult<TResult> benchmark(TResult (*function)(TParams...), TParams ...params){
    using namespace std::chrono;

    const auto begin = high_resolution_clock::now();
    auto result = function(std::forward<TParams>(params)...);
    const auto end = high_resolution_clock::now();

    return { std::move(result), duration_cast<Ratio>(end - begin).count() };
}

And for example,

int sleep(int seconds){
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(1s);

    return seconds * 1e6; // return the given second in microsecond unit
}

// (implement above code)

int main(){
    auto [elapsed_us, elapsed_ms] = benchmark<std::chrono::milliseconds>(sleep, 1);
    std::cout << "Elapsed ms: " << elapsed_ms << " Elapsed us: " << elapsed_us;;

    return 0;
}

Will output like

Elapsed ms: 1005 Elapsed us: 1000000

My goal is to change the argument type like BenchmarkResult<TResult> benchmark(std::function<TResult(TParams...)> function, TParams ...params). But it does not works for the above example in the latest C++ version.

The compiler says,

/main.cpp: In function 'int main()':
/main.cpp:76:73: error: no matching function for call to 'benchmark<std::chrono::milliseconds>(int (&)(int), int)'
   76 |     auto [elapsed_us, elapsed_ms] = benchmark<std::chrono::milliseconds>(sleep, 1);
      |                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~
/main.cpp:54:26: note: candidate: 'template<class Ratio, class TResult, class ... TParams> BenchmarkResult<TResult> benchmark(std::function<TResult(TParams ...)>, TParams ...)'
   54 | BenchmarkResult<TResult> benchmark(std::function<TResult(TParams...)> function, TParams ...params){ // TODO: use std::function instead of function pointer
      |                          ^~~~~~~~~
/main.cpp:54:26: note:   template argument deduction/substitution failed:
/main.cpp:76:73: note:   mismatched types 'std::function<TResult(TParams ...)>' and 'int (*)(int)'
   76 |     auto [elapsed_us, elapsed_ms] = benchmark<std::chrono::milliseconds>(sleep, 1);

How can I achieve this?


来源: stackexchange

问:
How can I annotate an object with its attribute?
from what I know is that object detection uses both (Localization + Classification) but this only for binary classification
but what if I want to detect an object and its attributes?

For example, detect a face

if a mask is worn correctly return 0, if a mask worn improperly 1, otherwise 2

if the person eats return 0 otherwise 1

if the person smokes return 0 otherwise 1

what kind this problem is? and how can I annotate and train it?

I tried to use multi bounding boxes but I don't think it is a good idea

ContentLicense: CC BY-SA 4.0


问:
rescan for macro replacement?
By reading here
(where I cannot add comments-questions as I am new on StackOverflow),
it is explained that with the definitions

```<code>#define foo(X) 1 bar
#define bar(X) 2 foo
</code>```

then

```<code>foo(X)(Y)(Z)
</code>```

expands to

```<code>1 2 1 bar
</code>```

In particular, the additional comment by @ H Walters on Jul 2, 2020 at 14:36 (see link above) reads
foo's replacement list (as in: "After all parameters in the replacement list have been substituted") is: 1 bar. That replacement list does not contain a bar invocation. foo is painted blue while 6.10.3.4p2 ("scan of the replacement list", also note "not including the rest of the source file's preprocessing tokens") occurs. Then, it's done, and foo is unpainted. Then you have 1 bar (Y)(Z). Then you have bar (Y) which is an invocation of bar; that invocation is not part of foo's rescan and replacement.

So, my question is:
why in this other scenario the same seems not to apply ?

```<code>#define t(a) a
</code>```

then

```<code>t(t)(1)
</code>```

expands to

```<code>t(1)
</code>```

...that is, 't' seems to remain painted.
Even the standard shows this case (as part of a more complex example, here I just extracted the nutshell I wanted to focus on).

An important detail: I look for it in C++ while the original post was on C99, but I guess it is the same.
Anyway, on g++ both scenarios work as explained above.

To recap:

```<code>#define t(a) a
#define k(a) a

k(t)(k)(1) -> expands to: 1 [both k and t never remain painted]
t(t)(1) -> expands to: t(1) [t remains painted]
t(t)(t)(t)(1) -> expands to t(t)(t)(1) [t remains painted after first replacement]
</code>```

Title: rescan for macro replacement?

Body:
By reading here
(where I cannot add comments-questions as I am new on StackOverflow),
it is explained that with the definitions

#define foo(X) 1 bar
#define bar(X) 2 foo

then

foo(X)(Y)(Z)

expands to

1 2 1 bar

In particular, the additional comment by @ H Walters on Jul 2, 2020 at 14:36 (see link above) reads
foo's replacement list (as in: "After all parameters in the replacement list have been substituted") is: 1 bar. That replacement list does not contain a bar invocation. foo is painted blue while 6.10.3.4p2 ("scan of the replacement list", also note "not including the rest of the source file's preprocessing tokens") occurs. Then, it's done, and foo is unpainted. Then you have 1 bar (Y)(Z). Then you have bar (Y) which is an invocation of bar; that invocation is not part of foo's rescan and replacement.

So, my question is:
why in this other scenario the same seems not to apply ?

#define t(a) a

then

t(t)(1)

expands to

t(1)

...that is, 't' seems to remain painted.
Even the standard shows this case (as part of a more complex example, here I just extracted the nutshell I wanted to focus on).

An important detail: I look for it in C++ while the original post was on C99, but I guess it is the same.
Anyway, on g++ both scenarios work as explained above.

To recap:

#define t(a) a
#define k(a) a

k(t)(k)(1) -> expands to: 1 [both k and t never remain painted]
t(t)(1) -> expands to: t(1) [t remains painted]
t(t)(t)(t)(1) -> expands to t(t)(t)(1) [t remains painted after first replacement]


问:
Powershell Invoke-WebRequest doesn't work with api key
I want to call an api and I can't because of the api key type authorization.

I leave you an example of how I call it via postman and it works for me:

This is the code that I have that doesn't work for me:

```<code><code>
$headers = @{Authorization="auth_token codeKeyhere"}
$params = @{
    Uri         = 'endopointhere'
    Method      = 'GET'
    ContentType = 'application/json'
}

$response =  Invoke-RestMethod @params -Header $header
$response
</code>
</code>```

Body:
I want to call an api and I can't because of the api key type authorization.

I leave you an example of how I call it via postman and it works for me:

This is the code that I have that doesn't work for me:

$headers = @{Authorization="auth_token codeKeyhere"}
$params = @{
    Uri         = 'endopointhere'
    Method      = 'GET'
    ContentType = 'application/json'
}

$response =  Invoke-RestMethod @params -Header $header
$response


问:
Can Glade show preview for menu?
I created a menu and clicked the preview button, but it only showed an empty window titled "glade-previewer". Is it possible to preview a menu?

Title: Can Glade show preview for menu?


问:
Can't initialize GTK backend in function 'cvInitSystem'
Here is my code:

```<code>import numpy
import cv2

cap = cv2.VideoCapture('/home/pi/butterfly/cut2.mp4')
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.open('/home/pi/butterfly/cut2.mp4')

if (cap.isOpened()==False):
    print("error in opening  video stream")
    exit()

fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter('cut2.mp4',fourcc,10,(800,480))

while(cap.isOpened()):
    ret,frame = cap.read()
    if ret == True:
        frame = cv2.flip(frame,0)
        out.write(frame)
        cv2.imshow('frame',frame)
        print("playvideo")
        # Press 'q' to quit
        if cv2.waitKey(25) & 0xFF == ord('q'):
                break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()
</code>```

Then It shows error below:

cv2.error: OpenCV(4.6.0) /tmp/pip-wheel-8c7uejek/opencv-python_88dbbad412c5416b992ae69de26299d6/opencv/modules/highgui/src/window_gtk.cpp:635: error: (-2:Unspecified error) Can't initialize GTK backend in function 'cvInitSystem'

How can I fix it? I am using the following versions:

```<code>python version 3.7
openCV version 4.6.0
gnu linux 10 tty1
</code>```

Body:
Here is my code:

import numpy
import cv2

cap = cv2.VideoCapture('/home/pi/butterfly/cut2.mp4')
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.open('/home/pi/butterfly/cut2.mp4')

if (cap.isOpened()==False):
    print("error in opening  video stream")
    exit()

fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter('cut2.mp4',fourcc,10,(800,480))

while(cap.isOpened()):
    ret,frame = cap.read()
    if ret == True:
        frame = cv2.flip(frame,0)
        out.write(frame)
        cv2.imshow('frame',frame)
        print("playvideo")
        # Press 'q' to quit
        if cv2.waitKey(25) & 0xFF == ord('q'):
                break
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()

Then It shows error below:

cv2.error: OpenCV(4.6.0) /tmp/pip-wheel-8c7uejek/opencv-python_88dbbad412c5416b992ae69de26299d6/opencv/modules/highgui/src/window_gtk.cpp:635: error: (-2:Unspecified error) Can't initialize GTK backend in function 'cvInitSystem'

How can I fix it? I am using the following versions:

python version 3.7
openCV version 4.6.0
gnu linux 10 tty1


问:
Leanback VerticalGridView height to wrap_content
I am trying to have a leanback VerticalGridView. Inside it I would like to have multmple VerticalGridView. The thing is that wrap_content is ignored by the layoutManager so that the grid height is only the height of one single item insted showing all of them.
I tried to set the layoutManager to a LinearLayoutManager(contenxt, VERTICAL, false) but problem still there. Also I have tried xml obvious options.

Any idea?


问:
strace compiled with aarch64-musl-gcc do not support -k option and can not track user space function?
I meet a problem these days. I ported strace for an aarch64 device and the compiler gcc I use is bond to musl not glibc. when I used -k option to track user space function I found that -k option is not supported.

So what can I do to make -k option come true even when musl does not support backtrace() under the conditions that I can not change the toolchain, can not change to glibc.


问:
user list table showing twice
I have list components:

```<code>import React,{useState,useEffect} from 'react'
import { Link } from 'react-router-dom'
import UserService from '../services/UserService'

const UserList = () => {

    const [users,setUsers] = useState([])

    useEffect(() => {
        UserService.findAll().then((response)=>{
            setUsers(response.data)

        }).catch(error=>{
            console.log(error)
        })
    },[users])
   const [selectedUserId, setSelectedUserId] = useState();

   const handleRowClick = (id) => {
    setSelectedUserId(id);
  }

  return (
    <div className='container'>
        <h2 className='text-center'>Users</h2>
        <div>
            <table className='table table-bordered table-stripped'>
                <thead>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Email</th>
                    <th>Password</th>
                </thead>
                <tbody>
                    {
                        users.map(
                            user =>

                            <tr key={user.id} onClick={() => handleRowClick(user.id)} style={{backgroundColor: selectedUserId === user.id ? "lightblue" : ""}}>
                                <td>{user.firstName}</td>
                                <td>{user.lastName}</td>
                                <td>{user.email}</td>
                                <td>{user.password}</td>
                            </tr>
                        )
                    }
                </tbody>
            </table>
        </div>
        <Link className="btn btn-primary mx-2" to={"/users/save"}  state='Create' >New</Link>
        <Link className="btn btn-primary mx-2" to={'/update/'+selectedUserId}  state='Update'> Edit</Link>
        <Link className="btn btn-primary mx-2" to={"/update/"+selectedUserId}   state='Delete' >Delete</Link>
    </div>
  )
}
export default UserList;
//<Link className="btn btn-primary mx-2" to={"/users/save"}  onClick={() => setData('Create')} >New</Link>
</code>```

It shows UserList twice:

I thought because of the React Strict Mode but it wasn't.

Why is my table showing twice? How can I fix this?

Title: user list table showing twice

Body:
I have list components:

import React,{useState,useEffect} from 'react'
import { Link } from 'react-router-dom'
import UserService from '../services/UserService'

const UserList = () => {

    const [users,setUsers] = useState([])

    useEffect(() => {
        UserService.findAll().then((response)=>{
            setUsers(response.data)

        }).catch(error=>{
            console.log(error)
        })
    },[users])
   const [selectedUserId, setSelectedUserId] = useState();

   const handleRowClick = (id) => {
    setSelectedUserId(id);
  }

  return (

Users

                    First Name
                    Last Name
                    Email
                    Password

                    {
                        users.map(
                            user =>

 handleRowClick(user.id)} style={{backgroundColor: selectedUserId === user.id ? "lightblue" : ""}}>
                                {user.firstName}
                                {user.lastName}
                                {user.email}
                                {user.password}

                        )
                    }

        <Link className="btn btn-primary mx-2" to={"/users/save"}  state='Create' >New</Link>
        <Link className="btn btn-primary mx-2" to={'/update/'+selectedUserId}  state='Update'> Edit</Link>
        <Link className="btn btn-primary mx-2" to={"/update/"+selectedUserId}   state='Delete' >Delete</Link>

  )
}
export default UserList;
//<Link className="btn btn-primary mx-2" to={"/users/save"}  onClick={() => setData('Create')} >New</Link>

It shows UserList twice:

I thought because of the React Strict Mode but it wasn't.

Why is my table showing twice? How can I fix this?


问:
Instagram Chatbot
There's someone that knows how to reply to Instagram new direct messages automatically?
I've build a python chatbot and I hope to use it to reply to messages but if it's not possible and Azure, AWS, GCP or any other service can be used it's ok. I'm avoiding web scraping.

The aim is to give customers informations about a product and NOT send spam messages to followers.

Searching on the web I understood that instagram API doesn't offer the possibility to reply messages, if I'm wrong and someone can provide me an example or some documentation I'm here!

So the questions are: it's possible to build an instagram bot? If yes, how?

Thanks for the help!

Title: Instagram Chatbot


问:
What is the purpose of CHAPTER END in video metadata?
I am learning how to use ffmpeg to add chapters to fairly long recordings as a mean of remembering key timestamps.
After a successful test I got my chapters showing in VLC as little marks on the time bar and in chapter menu, but those marks correspond to START time obviously.

So what is the purpose of END time? It does not seem to do anything in VLC, is it important to have a chapter starting at the start of the video and one ending at the end of the video? Is it important to have each chapter end when the next one starts?

```<code>[CHAPTER]
TIMEBASE=1/1
START=1
END=600
title=Chapter
</code>```

Body:
I am learning how to use ffmpeg to add chapters to fairly long recordings as a mean of remembering key timestamps.
After a successful test I got my chapters showing in VLC as little marks on the time bar and in chapter menu, but those marks correspond to START time obviously.

So what is the purpose of END time? It does not seem to do anything in VLC, is it important to have a chapter starting at the start of the video and one ending at the end of the video? Is it important to have each chapter end when the next one starts?

[CHAPTER]
TIMEBASE=1/1
START=1
END=600
title=Chapter


问:
iOS how to code UITableView multiple selection cell like message app, can up&down slide to select or unselect?
How to select messages in the message app? You can slide up and down to select multiple messages. Tableview will not slide along

![1]

I had set allowsMultipleSelectionDuringEditing to true, but can't select cell like message app. Only one click to select.


问:
Get Statement object from NamedJdbctemplate execute/query
How to properly get reference to the Statment object inside the NamedParameterJdbcTemplate query/exeucte/update.

I need the reference because I have a button on the GUI to stop the running query (connection.close() & statement.close() & release connection etc.)

I do not want to use plain jdbc because I need the extras that namedjdbctemplate provide.
I also don't want to use httprpc with plain jdbc because httprpc named paramters setter bugged when the sql statement contains :. (in regex, column names, or any char inside in an inner function)

So I want to use namedjdbctemplate for my queries and I also need the Connection and Statement object reference.

At nJdbcTemplate.query I could override the extract data and from the ResultSet I got it:

```<code>    var wrapper = new Object() {
        Statement value = null;
    };

    var columnWrapper = new Object() {
        List<Object> columnNames = null;
    };

    Statement statement = wrapper.value;
    task.setPreparedStatement(statement);

    String sql = reportTab.getSqlStatement();

    try {
        List<List<Object>> query = nJdbcTemplate.query(sql, paramMap, new ResultSetExtractor<List<List<Object>>>() {

            @Override
            public List<List<Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {

                wrapper.value = rs.getStatement();

                List<Object> columnNames = getColumnNames(rs);
                columnWrapper.columnNames = columnNames;
</code>```

My main problem is that I cannot get it when I have to use execute/update

I tried with this, but when I use DLL the resultset is null.

```<code>        Object result = nJdbcTemplate.execute(sql, paramMap, (PreparedStatementCallback<Object>) ps -> {
            ResultSet resultSet = ps.getResultSet();
            Statement statement2 = resultSet.getStatement();
            wrapper.value = statement2;
            ps.executeUpdate();
            return "result";
        });
</code>```

Body:
How to properly get reference to the Statment object inside the NamedParameterJdbcTemplate query/exeucte/update.

I need the reference because I have a button on the GUI to stop the running query (connection.close() & statement.close() & release connection etc.)

I do not want to use plain jdbc because I need the extras that namedjdbctemplate provide.
I also don't want to use httprpc with plain jdbc because httprpc named paramters setter bugged when the sql statement contains :. (in regex, column names, or any char inside in an inner function)

So I want to use namedjdbctemplate for my queries and I also need the Connection and Statement object reference.

At nJdbcTemplate.query I could override the extract data and from the ResultSet I got it:

    var wrapper = new Object() {
        Statement value = null;
    };

    var columnWrapper = new Object() {
        List<Object> columnNames = null;
    };

    Statement statement = wrapper.value;
    task.setPreparedStatement(statement);

    String sql = reportTab.getSqlStatement();

    try {
        List<List<Object>> query = nJdbcTemplate.query(sql, paramMap, new ResultSetExtractor<List<List<Object>>>() {

            @Override
            public List<List<Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {

                wrapper.value = rs.getStatement();

                List<Object> columnNames = getColumnNames(rs);
                columnWrapper.columnNames = columnNames;

My main problem is that I cannot get it when I have to use execute/update

I tried with this, but when I use DLL the resultset is null.

        Object result = nJdbcTemplate.execute(sql, paramMap, (PreparedStatementCallback<Object>) ps -> {
            ResultSet resultSet = ps.getResultSet();
            Statement statement2 = resultSet.getStatement();
            wrapper.value = statement2;
            ps.executeUpdate();
            return "result";
        });


问:
cannot import ngx-gauge to Razor Pages
i cannot include ngx-gauge component to my Razor Pages application. Dont know why, but it didnt shows after installing npm package. Any ideas why it is not working? This is example from dev tool. https://www.npmjs.com/package/ngx-gauge</p>
```<code><ngx-gauge [type]="gaugeType"
           [value]="gaugeValue"
           [label]="gaugeLabel"
           [append]="gaugeAppendText">
</ngx-gauge>
</code>```

Title: cannot import ngx-gauge to Razor Pages

Body:
i cannot include ngx-gauge component to my Razor Pages application. Dont know why, but it didnt shows after installing npm package. Any ideas why it is not working? This is example from dev tool. https://www.npmjs.com/package/ngx-gauge

<ngx-gauge [type]="gaugeType"
           [value]="gaugeValue"
           [label]="gaugeLabel"
           [append]="gaugeAppendText">
</ngx-gauge>


问:
I received data normally with socket emit, but refetching is not working
I am using useState Hook to get setList values, users state values, and data values from socket.on(users).

However, my problem is that I receive the data normally, but when the data changes on the server, the list state value should be refetched, but it is not being refetched.

How can I refetch the list value in useEffect to automatically render it when the data is updated on the server?

I put a list in useEffect deps out of curiosity, but re-rendering occurs by calling the list infinitely.

```<code>  const [list, setList] = useState<any>([]);

useEffect(() => {
    socket.on("connect", () => {
    });

    socket.on("users", (data: any) => {
      setList(data);
    });

    socket.emit(users);
    return () => {
      socket.off(users);
    };
  }, [socket]);

</code>```

Body:
I am using useState Hook to get setList values, users state values, and data values from socket.on(users).

However, my problem is that I receive the data normally, but when the data changes on the server, the list state value should be refetched, but it is not being refetched.

How can I refetch the list value in useEffect to automatically render it when the data is updated on the server?

I put a list in useEffect deps out of curiosity, but re-rendering occurs by calling the list infinitely.

  const [list, setList] = useState<any>([]);

useEffect(() => {
    socket.on("connect", () => {
    });

    socket.on("users", (data: any) => {
      setList(data);
    });

    socket.emit(users);
    return () => {
      socket.off(users);
    };
  }, [socket]);


问:
ESP8266 AsyncWebServerRequest handle incoming JSON request
I am building a project with ESP8266, SPIFFS and AsyncWebServerRequest.
The idea is to have a config.json file in the FS, that the ESP reads on start.
The config is big(around 2K) because it stores a lot of variables.
In addition I have index.html page, that I serve to the client via AsyncWebServerRequest

```<code>  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", "text/html");
  });

</code>```

When the page is loaded it makes second request to the ESP for the configuration and uses JS to propagate the configuration to the fields.
When you change the config from the web-page and click "Save Config" it encodes the form data in to JSON and make another request to the ESP(POST Request "Content-Type", "application/json" with the config. When the config is small it looks OK, but when the config is bigger it starts adding unidentified chars. I am not sure if I collect the http body properly:

```<code>server.on(
    "/config/upload",
    HTTP_POST,
    [](AsyncWebServerRequest * request){},
    NULL,
    [](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
      for (size_t i = 0; i < len; i++) {
        conf_f+=char(data[i]);
      }
      newConfig = 1;
      request->send(200);
  });
</code>```

I think the issue is with the async, because it interrupts the concatenation process of the String. When I Serial.print the chars one by one it adds two of three new lines, that do not even have a char code.
Here is an example of the end of the config after failed upload: "enabled":"1","modbus_refresh_rate":"5","slaves_count":1���

This of course disrupt the ArduinoJSON and the system is not booting with the correct config.

My question is: Is there a better way to manipulate the HTTP body, because the one I am using looks wrong.

Body:
I am building a project with ESP8266, SPIFFS and AsyncWebServerRequest.
The idea is to have a config.json file in the FS, that the ESP reads on start.
The config is big(around 2K) because it stores a lot of variables.
In addition I have index.html page, that I serve to the client via AsyncWebServerRequest

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", "text/html");
  });

When the page is loaded it makes second request to the ESP for the configuration and uses JS to propagate the configuration to the fields.
When you change the config from the web-page and click "Save Config" it encodes the form data in to JSON and make another request to the ESP(POST Request "Content-Type", "application/json" with the config. When the config is small it looks OK, but when the config is bigger it starts adding unidentified chars. I am not sure if I collect the http body properly:

server.on(
    "/config/upload",
    HTTP_POST,
    [](AsyncWebServerRequest * request){},
    NULL,
    [](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
      for (size_t i = 0; i < len; i++) {
        conf_f+=char(data[i]);
      }
      newConfig = 1;
      request->send(200);
  });

I think the issue is with the async, because it interrupts the concatenation process of the String. When I Serial.print the chars one by one it adds two of three new lines, that do not even have a char code.
Here is an example of the end of the config after failed upload: "enabled":"1","modbus_refresh_rate":"5","slaves_count":1���

This of course disrupt the ArduinoJSON and the system is not booting with the correct config.

My question is: Is there a better way to manipulate the HTTP body, because the one I am using looks wrong.


问:
How do I fix Laravel JWT "logging in Argument #2 must be of type array, string given" problem?
I'm using this package however, I don't think the problem comes from the package.

If I try to log in my user like this

```<code>auth()->attempt(['email'=>'testing2@gmail.com', 'password'=>'thepassword'])
</code>```

I'll get this error

```<code>array_merge(): Argument #2 must be of type array, string given in vendor\psy\psysh\src\Exception\TypeErrorException.php on line 53.
</code>```

according to that error it has something to do with the second argument being array so i played along and did this

```<code>auth()->attempt(['email'=>'testing2@gmail.com', 'password'=>'thepassword'], [])
</code>```

and it returns

```<code>true
</code>```

at first i thought it was the auth guard but i after i checked it was fine

```<code>'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],
</code>```

I went through every step in the docs the quick start and still found nothing

Body:
I'm using this package however, I don't think the problem comes from the package.

If I try to log in my user like this

auth()->attempt(['email'=>'testing2@gmail.com', 'password'=>'thepassword'])

I'll get this error

array_merge(): Argument #2 must be of type array, string given in vendor\psy\psysh\src\Exception\TypeErrorException.php on line 53.

according to that error it has something to do with the second argument being array so i played along and did this

auth()->attempt(['email'=>'testing2@gmail.com', 'password'=>'thepassword'], [])

and it returns

true

at first i thought it was the auth guard but i after i checked it was fine

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

I went through every step in the docs the quick start and still found nothing


问:
Using Nuxt 3 public directory without rebuilding
The public dir does not work in Nuxt 3 as a static dir in Nuxt 2. In Nuxt 2 I used the backend to put dynamic content in static, and then used in the application. In Nuxt 3 from the public dir the public content is placed in the .output and .nuxt/dist/server and .nuxt/dist/client dirs during the build of the project and pulled from there. Where to put files dynamicly so that they can be used in app without rebuilding the application?


问:
Download an excel from an api response
When try to download excel from api response, the api result is success but when it  enter into,  a.href = URL.createObjectURL(b64toBlob(res.data, "application/excel")) this code after this code it automatically goes to catch. Why this happen? How to resolve this issue?

Title: Download an excel from an api response


问:
How to disable both past date and time in material-ui textfield datepicker
I have added the following code in the textfield (datetime-local) to disable the past dates:

```<code>inputProps={{
        min: new Date().toISOString().slice(0, 16),
      }}
</code>```

But It only disable the past dates. I also want to disable the past time.

Body:
I have added the following code in the textfield (datetime-local) to disable the past dates:

inputProps={{
        min: new Date().toISOString().slice(0, 16),
      }}

But It only disable the past dates. I also want to disable the past time.


问:
getAuth defined in module cannot be used. getAuth not defined
Hi i have imported getAuth in   but when I try to use getAuth in the body it errors "Uncaught ReferenceError: getAuth is not defined"

error on this line const auth = getAuth(); in function SignIn

how can I resolve this please

this is the project

```<code><html>
<head>
  <!--jquery, bootstrap css, firebase-->

  <!--jquery-->
  <script
    src="https://code.jquery.com/jquery-3.6.2.min.js"
    integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA="
    crossorigin="anonymous">
  </script>

  <!--bootstrap-->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script>

  <script type="module">
    // Import the functions you need from the SDKs you need

    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js";
    import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js';
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries

    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "xx",
      authDomain: "xx-22.firebaseapp.com",
      projectId: "xx-22",
      storageBucket: "xx-22.appspot.com",
      messagingSenderId: "222",
      appId: "1:22:web:ccxxx",
      measurementId: "G-cccc"
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
  </script>
</head>
<body>
  <!--login form-->
  <div class="container" id="login-form">
    <div class="well">
      <form>
        <div class="mb-3">
          <label for="inputEmail" class="form-label">Email address</label>
          <input type="email" class="form-control" id="inputEmail" placeholder="name@example.com">
        </div>
        <div class="mb-3">
          <label for="inputPassword" class="form-label">Password</label>
          <input type="password" class="form-control" id="inputPassword" placeholder="password">
        </div>
        <div class="d-grid gap-2">
          <button type="button" id="sign-in-button" class="btn btn-primary">Sign in</button>
        </div>
        <div class="d-grid gap-2">
          <button type="button" id="create-newuser-button" class="btn btn-warning">Create new account</button>
        </div>
        <div class="d-grid gap-2">
          <button type="button" id="google-login-button" class="btn btn-primary">Sign in with Google</button>
        </div>
      </form>
    </div>
  </div>

  <!--add hero form-->
  <div class="container" id="login-form">
    <div class="well">
      <form>
        <div class="mb-3">
          <label for="inputHeroname" class="form-label">Hero name</label>
          <input type="text" class="form-control" id="inputHeroName" placeholder="hero name">
        </div>
        <div class="d-grid gap-2">
          <button type="button" id="create-newhero-button" class="btn btn-primary">reate new hero</button>
        </div>
      </form>
    </div>
  </div>

  <!--scripts-->
  <script>
    $("#create-newuser-button").click(function() {
      var email = $("inputEmail").val()
      var password = $("inputPassword").val()
      console.log("new user = " + email + " password - " + password)
      SignIn(email, password)
    });

    function SignIn(email, password) {
      const auth = getAuth(); //error here
      createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
          // Signed in
          const user = userCredential.user;
          // ...
        })
        .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          console.log(error)
          // ..
        });
    }
  </script>
</body>
</code>```

your help ins much appreciated

thanks
R

Body:
Hi i have imported getAuth in   but when I try to use getAuth in the body it errors "Uncaught ReferenceError: getAuth is not defined"

error on this line const auth = getAuth(); in function SignIn

how can I resolve this please

this is the project

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

      <form>

          Email address
          <input type="email" class="form-control" id="inputEmail" placeholder="name@example.com">

          Password
          <input type="password" class="form-control" id="inputPassword" placeholder="password">

          <button type="button" id="sign-in-button" class="btn btn-primary">Sign in</button>

          <button type="button" id="create-newuser-button" class="btn btn-warning">Create new account</button>

          <button type="button" id="google-login-button" class="btn btn-primary">Sign in with Google</button>

      </form>

      <form>

          Hero name
          <input type="text" class="form-control" id="inputHeroName" placeholder="hero name">

          <button type="button" id="create-newhero-button" class="btn btn-primary">reate new hero</button>

      </form>

your help ins much appreciated

thanks
R


问:
Calling variadic printf() from variadic C++ function
There are 2 ways of doing it:

template<class arg, class... args>
void test1(arg format, args... va)
{
    printf(format, va...);
}

void test2(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
}

test1("x = %i, pi = %.2f.\r\n", 42, 3.1415926535);
test2("x = %i, pi = %.2f.\r\n", 42, 3.1415926535);
```

Both function do the same, what are the pros and cons of each approach?

When I google for "variadic functions in C++" I get the C style stdarg answer first.
Then "see variadic templates...".

I've read about both, and for the first glance the templated function seems neater. Shorter code, much more readable. But are there any catches? Which one is faster?

Body:
There are 2 ways of doing it:

template<class arg, class... args>
void test1(arg format, args... va)
{
    printf(format, va...);
}

void test2(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
}

test1("x = %i, pi = %.2f.\r\n", 42, 3.1415926535);
test2("x = %i, pi = %.2f.\r\n", 42, 3.1415926535);

Both function do the same, what are the pros and cons of each approach?

When I google for "variadic functions in C++" I get the C style stdarg answer first.
Then "see variadic templates...".

I've read about both, and for the first glance the templated function seems neater. Shorter code, much more readable. But are there any catches? Which one is faster?


问:
You cannot use different slug names for the same dynamic pat
I want to npm run build on nextjs project but give me this error:

you cannot use different slug names for the same dynamic path ('category' !== 'slug')

This my page directory:

Any idea what's wrong? I don't have a duplicate slug name even!


问:
How to detect the double tap and hold gesture when accessibility is on?
I have an app that displays a link when you scan a QR code.
With accessibility turned on (VoiceOver):
When I double click on the link I open a custom alert.
The problem is that when I double-click and hold on the link I still get the alert instead of the context menu.

My code:

```<code>- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {

    BOOL linkScheme = ([URL.scheme isEqualToString: @"http"] || [URL.scheme isEqualToString: @"https"]);

    if ([[UIApplication sharedApplication] canOpenURL:URL]){
        NSUserDefaults *saveURL = [NSUserDefaults standardUserDefaults];
        [saveURL setObject:URL.absoluteString forKey:@"SavedURL"];
        [saveURL synchronize];

        if (linkScheme) {
//          if (detect double click and hold) {
                return YES;
            } else {
                if(!GUIManager.instance.isAlwaysAskChecked){
                    if(GUIManager.instance.openInThisAppButtonChecked) {
                        UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
                        while (topController.presentedViewController) {
                            topController = topController.presentedViewController;
                        }
                        WebViewController* webView = [[WebViewController alloc] init];
                        [topController showViewController:webView sender:nil];
                    } else {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL.absoluteString]];
                    }
                } else {
                    tableV.accessibilityElementsHidden = YES;

                    AlertView* alertView = [[AlertView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
                    [self.view addSubview: alertView];

                    UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, alertView);
                }
                return NO;
            }
        }
    }
    return YES;
}
</code>```

I'd like to enable the context menu on double-click and hold (with accessibility (VoiceOver) enabled), instead of displaying an alert.

Body:
I have an app that displays a link when you scan a QR code.
With accessibility turned on (VoiceOver):
When I double click on the link I open a custom alert.
The problem is that when I double-click and hold on the link I still get the alert instead of the context menu.

My code:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {

    BOOL linkScheme = ([URL.scheme isEqualToString: @"http"] || [URL.scheme isEqualToString: @"https"]);

    if ([[UIApplication sharedApplication] canOpenURL:URL]){
        NSUserDefaults *saveURL = [NSUserDefaults standardUserDefaults];
        [saveURL setObject:URL.absoluteString forKey:@"SavedURL"];
        [saveURL synchronize];

        if (linkScheme) {
//          if (detect double click and hold) {
                return YES;
            } else {
                if(!GUIManager.instance.isAlwaysAskChecked){
                    if(GUIManager.instance.openInThisAppButtonChecked) {
                        UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
                        while (topController.presentedViewController) {
                            topController = topController.presentedViewController;
                        }
                        WebViewController* webView = [[WebViewController alloc] init];
                        [topController showViewController:webView sender:nil];
                    } else {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URL.absoluteString]];
                    }
                } else {
                    tableV.accessibilityElementsHidden = YES;

                    AlertView* alertView = [[AlertView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
                    [self.view addSubview: alertView];

                    UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, alertView);
                }
                return NO;
            }
        }
    }
    return YES;
}

I'd like to enable the context menu on double-click and hold (with accessibility (VoiceOver) enabled), instead of displaying an alert.


问:
Having clause not filter some rows
Have query which calculates average scores by users, want to add condition to show score in some range

```<code>Select byUserAndQ.email, byUserAndQ.userName,
        round( avg(byUserAndQ.innerScore) ) as score,
        round( avg (byUserAndQ.innerScore) ) >=50 as inRange
from (
        SELECT  tu.email, tu.name as userName,
                sum(ta.score)/q.max_score*100 as innerScore
        FROM test  t
            INNER JOIN test_user tu ON tu.test_id = t.id
            LEFT JOIN  test_action ta on ta.test_id = t.id and ta.email = tu.email
            LEFT JOIN question  q ON q.id = ta.question_id
        WHERE t.id = 144
        AND tu.email IS NOT NULL
        GROUP BY tu.email, q.id ) as byUserAndQ
group by byUserAndQ.email
having  score>= 50
</code>```

returns me all rows instead score>=50:

```<code>user1@example.com, User1,56,1
user2@example.com, User2,28,0
user3@example.com,User3,78,1
</code>```

if I remove , byUser.userName from top select -  it working fine. which is very strange for me. I think Having should be applied to final data, so no matter which fields else in result.

Also tried to group by name as well - without success:

```<code>Select byUserAndQ.email, byUserAndQ.userName,
        round( avg(byUserAndQ.innerScore) ) as score,
        round( avg (byUserAndQ.innerScore) ) >=50 as inRange
from (SELECT tu.email, tu.name as userName,
            sum(ta.score)/q.max_score*100 as innerScore
      FROM test  t
        INNER JOIN test_user tu ON tu.test_id = t.id
        LEFT JOIN  test_action ta on ta.test_id = t.id and ta.email = tu.email
        LEFT JOIN question  q ON q.id = ta.question_id
        WHERE t.id = 144
        AND tu.email IS NOT NULL
        GROUP BY tu.email, tu.name, q.id
    ) as byUserAndQ
group by  byUserAndQ.email, byUserAndQ.userName
having  score>= 50
</code>```

wrapping in another subquery with where  works fine as well:

```<code>   select * from (Select byUser.email, byUser.userName, round( avg(byUser.innerScore) ) as score, round( avg (byUser.innerScore) ) >=50 as inRange
   from (SELECT
   tu.email, tu.name as userName,
   sum(ta.score)/q.max_score*100 as innerScore
   FROM test  t
   INNER JOIN test_user tu ON tu.test_id = t.id
   LEFT JOIN  test_action ta on ta.test_id = t.id and ta.email = tu.email
   LEFT JOIN question  q ON q.id = ta.question_id
   WHERE t.id = 144
   AND tu.email IS NOT NULL
   GROUP BY tu.email, q.id ) as byUser
   group by  byUser.email ) as final
   where  score>= 50
</code>```

Why its working in such way?
MySql version: 5.7.12( AWS Serverless RDS )

Title: Having clause not filter some rows

Body:
Have query which calculates average scores by users, want to add condition to show score in some range

Select byUserAndQ.email, byUserAndQ.userName,
        round( avg(byUserAndQ.innerScore) ) as score,
        round( avg (byUserAndQ.innerScore) ) >=50 as inRange
from (
        SELECT  tu.email, tu.name as userName,
                sum(ta.score)/q.max_score*100 as innerScore
        FROM test  t
            INNER JOIN test_user tu ON tu.test_id = t.id
            LEFT JOIN  test_action ta on ta.test_id = t.id and ta.email = tu.email
            LEFT JOIN question  q ON q.id = ta.question_id
        WHERE t.id = 144
        AND tu.email IS NOT NULL
        GROUP BY tu.email, q.id ) as byUserAndQ
group by byUserAndQ.email
having  score>= 50

returns me all rows instead score>=50:

user1@example.com, User1,56,1
user2@example.com, User2,28,0
user3@example.com,User3,78,1

if I remove , byUser.userName from top select -  it working fine. which is very strange for me. I think Having should be applied to final data, so no matter which fields else in result.

Also tried to group by name as well - without success:

Select byUserAndQ.email, byUserAndQ.userName,
        round( avg(byUserAndQ.innerScore) ) as score,
        round( avg (byUserAndQ.innerScore) ) >=50 as inRange
from (SELECT tu.email, tu.name as userName,
            sum(ta.score)/q.max_score*100 as innerScore
      FROM test  t
        INNER JOIN test_user tu ON tu.test_id = t.id
        LEFT JOIN  test_action ta on ta.test_id = t.id and ta.email = tu.email
        LEFT JOIN question  q ON q.id = ta.question_id
        WHERE t.id = 144
        AND tu.email IS NOT NULL
        GROUP BY tu.email, tu.name, q.id
    ) as byUserAndQ
group by  byUserAndQ.email, byUserAndQ.userName
having  score>= 50

wrapping in another subquery with where  works fine as well:

   select * from (Select byUser.email, byUser.userName, round( avg(byUser.innerScore) ) as score, round( avg (byUser.innerScore) ) >=50 as inRange
   from (SELECT
   tu.email, tu.name as userName,
   sum(ta.score)/q.max_score*100 as innerScore
   FROM test  t
   INNER JOIN test_user tu ON tu.test_id = t.id
   LEFT JOIN  test_action ta on ta.test_id = t.id and ta.email = tu.email
   LEFT JOIN question  q ON q.id = ta.question_id
   WHERE t.id = 144
   AND tu.email IS NOT NULL
   GROUP BY tu.email, q.id ) as byUser
   group by  byUser.email ) as final
   where  score>= 50

Why its working in such way?
MySql version: 5.7.12( AWS Serverless RDS )


问:
Laravel all routes except home page '/' return 404
As the title says, all the routes in my laravel app except the home('/') route result in a 404 error.
it works in local server but in production in Ubuntu server return 404.

That is the .htaccess in public folder

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

</code>```

Body:
As the title says, all the routes in my laravel app except the home('/') route result in a 404 error.
it works in local server but in production in Ubuntu server return 404.

That is the .htaccess in public folder

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>


问:
Anyway for FreeRADIUS to rotate secrets based on lifetimes?
Even if it's not natively supported, I hope someone might have a novel way of implementing a time based rotation for a FreeRADIUS secret.  Or even better, similar to how certain networking device do it, a receive-lifetime and a transmit-lifetime.

I can't find anything that seems to do what I'm looking for, hopefully someone has some idea or pointers?

Or maybe a different RADIUS implementation that supports it?

I've tried a basic mix of a wildcard and specific IP but it seems to go the specific each time.  I thought maybe when the client rotates, it will fail at the wildcard and move to the more specific, but it just picks the more specific all the time, and then fails when the client rotates.

```<code>client all-clients {
        ipaddr = *
        secret = secret1
}
client devA {
        ipaddr = 1.1.1.1
        secret = secret2
}
</code>```

Thanks :-)

Body:
Even if it's not natively supported, I hope someone might have a novel way of implementing a time based rotation for a FreeRADIUS secret.  Or even better, similar to how certain networking device do it, a receive-lifetime and a transmit-lifetime.

I can't find anything that seems to do what I'm looking for, hopefully someone has some idea or pointers?

Or maybe a different RADIUS implementation that supports it?

I've tried a basic mix of a wildcard and specific IP but it seems to go the specific each time.  I thought maybe when the client rotates, it will fail at the wildcard and move to the more specific, but it just picks the more specific all the time, and then fails when the client rotates.

client all-clients {
        ipaddr = *
        secret = secret1
}
client devA {
        ipaddr = 1.1.1.1
        secret = secret2
}

Thanks :-)


问:
Select event - Why is nothing displayed in the console?
Why is nothing displayed in the console when selecting text?

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    dhksdh lsjkdlskdj s fjlkfjs d lsdjslkdj s sldjsldkj s
    <script>
        const onSelect = () => {
            console.log('onSelect text')
        }

        document.body.addEventListener('select', onSelect)
    </script>
</body>

</html>
</code>```

Maybe I wrote something wrong?

Body:
Why is nothing displayed in the console when selecting text?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    dhksdh lsjkdlskdj s fjlkfjs d lsdjslkdj s sldjsldkj s

Maybe I wrote something wrong?


问:
Why does JavaSystem.LoadLibrary() throw an UnsatisfiedLinkError despite the library existing in project?
I try to embedd an external library to my .Net MAUI project, but am unable to.

Following the process in this question:

I copied the .so file into
<project root>\Resources\lib\<platform>\ (the platforms being arm64-v8a, armeabi-v7a and x86_64).

Then set the Build Action = AndroidNativeLibrary for the file

I set the <AndroidNativeLibrary Include="Resources\lib\<platform>" /> in my .csproj file

Then I call JavaSystem.LoadLibrary(lib name); in the MainActivity.cs file of the Android project (which is my target platform)

As soon as my App is starting I receive a Java.Lang.UnsatisfiedLinkgError: 'dlopen failed: library libc++_shared.so" not found'

Why do I get this Error? My interpretation is, that the path to my library is wrong or the file is not correctly included into the build process, but I don't know why my previous steps are not sufficient.

I already tried to solve this by:

moving the path of the .so file into the platform specific folders \Platforms\Android\lib\<platform>

changing the <CopyToOutputDirectory></CopyToOutputDirectory> to various options

Unfortunately without success.

Edit: Fixing a typo


问:
How to mask two different videos in android programmatically?
Functionality - I want to mask two videos together in android.

I am able to stick a textview inside a stickerview, but I want to fit a playing video inside a stickerview and later on allow the videoStickerView to Mask itself with another video.

If anyone has a way to achieve it, please do input your answers to help me out here, it is completely okay with me to change the current way of implementation.

I just want this functionality to work.


问:
How to stop CORS error when sending headers?
I want to be connected to a remote API through AJAX via http://localhost:5500. This is my code with a sample URL:

```<code>$.ajax({
    url: "https://api.website.com/",
    headers: { 'x-api-key': 'Sd6g8uieEk8couufkxv9MVp5xdDJBcTSA' },
    type: "GET",
    withCredentials: false,
    success: function(data) { console.log(data) }
});
</code>```

If I remove the x-api-key part from this code, I have not any issue and receive responses. But, as I add this section to the code, I receive CORS errors:

Access to XMLHttpRequest at
'https://api.website.com/' from origin
'http://localhost:5500' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have
HTTP ok status.

I have added different settings in the .htaccess file, but they could not solve the issue:

```<code>Header add Access-Control-Allow-Origin "http://localhost:5500"
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "GET, POST, PUT, PATCH, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers: *
</code>```

I have read many articles, and did many changes on settings, but I could not solve the issue. May you help me please?

Body:
I want to be connected to a remote API through AJAX via http://localhost:5500. This is my code with a sample URL:

$.ajax({
    url: "https://api.website.com/",
    headers: { 'x-api-key': 'Sd6g8uieEk8couufkxv9MVp5xdDJBcTSA' },
    type: "GET",
    withCredentials: false,
    success: function(data) { console.log(data) }
});

If I remove the x-api-key part from this code, I have not any issue and receive responses. But, as I add this section to the code, I receive CORS errors:

Access to XMLHttpRequest at
'https://api.website.com/' from origin
'http://localhost:5500' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have
HTTP ok status.

I have added different settings in the .htaccess file, but they could not solve the issue:

Header add Access-Control-Allow-Origin "http://localhost:5500"
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "GET, POST, PUT, PATCH, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers: *

I have read many articles, and did many changes on settings, but I could not solve the issue. May you help me please?


问:
How should I host my data analysis pipeline?
for a project of mine I'm doing many experiments on data analysis over IOT events (storead on a Clickhouse server by the way). Now I've started to get some results of it, and I would like to set up a "near real time" pipeline to keep analyzing the data. Some sort of ETL with some ML on it.
My common platform for back-end development is .NET, but I'm not sure this is the right one for the job, as my pipeline is based on many Python libraries and technologies. I have had a look to Apache Spark, and it seems quite promising, but I would like some opinions from you. Am I going to the right direction? Should I try something different?

I've tryed to set up a Python service in a standalone mode, but not sure it's the right path


问:
Loading script dynamically works with remote link but not with downloaded code
I am trying to load a script dynamically in React, it works, however only if I link it directly from GitHub like this:

```<code>  const createScript = () => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://bernardo-castilho.github.io/DragDropTouch/DragDropTouch.js';
    script.onload = function () {
      setScriptLoadingState('LOADED');
      console.log('Script loaded');
    };
    script.onerror = function () {
      setScriptLoadingState('FAILED');
    };
    document.body.appendChild(script);
  };
</code>```

I want to load it from a script located in my folders after I have downloaded it like such, but it doesn't work:

```<code>  const createScript = () => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = './polyfill.js';
    script.onload = function () {
      setScriptLoadingState('LOADED');
      console.log('Script loaded');
    };
    script.onerror = function () {
      setScriptLoadingState('FAILED');
    };
    document.body.appendChild(script);
  };
</code>```

What am I doing wrong here and how can I load it successfully from a local folder dynamically as well?

Here is my full code:

```<code>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {
  Scheduler,
  WeekView,
  MonthView,
} from '@progress/kendo-react-scheduler';

import { Grid, GridColumn } from '@progress/kendo-react-grid';

import gridData from './data.js';

const App = () => {
  const MyScheduler = React.createRef();
  const [data, setData] = React.useState([]);
  const [dragItem, setDragItem] = React.useState('');
  const [width, setWidth] = React.useState(window.innerWidth);
  const [scriptLoadingState, setScriptLoadingState] = React.useState('IDLE');

  const createScript = () => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = './polyfill.js';
    script.onload = function () {
      setScriptLoadingState('LOADED');
      console.log('Script loaded');
    };
    script.onerror = function () {
      setScriptLoadingState('FAILED');
    };
    document.body.appendChild(script);
  };

  const handleDropItem = (e) => {
    let start = e.target.getAttribute('data-slot-start');
    let end = e.target.getAttribute('data-slot-end');
    let startDate = new Date(parseInt(start));
    let endDate = new Date(parseInt(end));
    let newEvent = {
      id: dragItem.taskID,
      title: dragItem.title,
      StartTimezone: null,
      start: startDate,
      end: endDate,
    };
    setData([newEvent, ...data]);
  };
  React.useEffect(() => {
    createScript();

    window.addEventListener('resize', handleWindowSizeChange);
    let schedulerElement = MyScheduler.current.element;
    schedulerElement.addEventListener('drop', handleDropItem);
    schedulerElement.addEventListener('dragover', (e) => e.preventDefault());

  });

  const GridRowRender = (tr, props) => {
    const trProps = {
      draggable: true,
      onDragStart: (e) => {
        setDragItem(props.dataItem);
      },
    };
    return React.cloneElement(tr, { ...trProps }, tr.props.children);
  };
  return (
    <>
      <Scheduler
        data={data}
        defaultDate={new Date('2013/6/13')}
        ref={MyScheduler}
      >
        <WeekView showWorkHours={false} />
        <MonthView />
      </Scheduler>
      <hr />
      <Grid data={gridData} rowRender={GridRowRender}>
        <GridColumn field="taskID" />
        <GridColumn field="title" />
      </Grid>
    </>
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));
</code>```

Body:
I am trying to load a script dynamically in React, it works, however only if I link it directly from GitHub like this:

  const createScript = () => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://bernardo-castilho.github.io/DragDropTouch/DragDropTouch.js';
    script.onload = function () {
      setScriptLoadingState('LOADED');
      console.log('Script loaded');
    };
    script.onerror = function () {
      setScriptLoadingState('FAILED');
    };
    document.body.appendChild(script);
  };

I want to load it from a script located in my folders after I have downloaded it like such, but it doesn't work:

  const createScript = () => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = './polyfill.js';
    script.onload = function () {
      setScriptLoadingState('LOADED');
      console.log('Script loaded');
    };
    script.onerror = function () {
      setScriptLoadingState('FAILED');
    };
    document.body.appendChild(script);
  };

What am I doing wrong here and how can I load it successfully from a local folder dynamically as well?

Here is my full code:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {
  Scheduler,
  WeekView,
  MonthView,
} from '@progress/kendo-react-scheduler';

import { Grid, GridColumn } from '@progress/kendo-react-grid';

import gridData from './data.js';

const App = () => {
  const MyScheduler = React.createRef();
  const [data, setData] = React.useState([]);
  const [dragItem, setDragItem] = React.useState('');
  const [width, setWidth] = React.useState(window.innerWidth);
  const [scriptLoadingState, setScriptLoadingState] = React.useState('IDLE');

  const createScript = () => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = './polyfill.js';
    script.onload = function () {
      setScriptLoadingState('LOADED');
      console.log('Script loaded');
    };
    script.onerror = function () {
      setScriptLoadingState('FAILED');
    };
    document.body.appendChild(script);
  };

  const handleDropItem = (e) => {
    let start = e.target.getAttribute('data-slot-start');
    let end = e.target.getAttribute('data-slot-end');
    let startDate = new Date(parseInt(start));
    let endDate = new Date(parseInt(end));
    let newEvent = {
      id: dragItem.taskID,
      title: dragItem.title,
      StartTimezone: null,
      start: startDate,
      end: endDate,
    };
    setData([newEvent, ...data]);
  };
  React.useEffect(() => {
    createScript();

    window.addEventListener('resize', handleWindowSizeChange);
    let schedulerElement = MyScheduler.current.element;
    schedulerElement.addEventListener('drop', handleDropItem);
    schedulerElement.addEventListener('dragover', (e) => e.preventDefault());

  });

  const GridRowRender = (tr, props) => {
    const trProps = {
      draggable: true,
      onDragStart: (e) => {
        setDragItem(props.dataItem);
      },
    };
    return React.cloneElement(tr, { ...trProps }, tr.props.children);
  };
  return (
    <>
      <Scheduler
        data={data}
        defaultDate={new Date('2013/6/13')}
        ref={MyScheduler}
      >
        <WeekView showWorkHours={false} />
        <MonthView />
      </Scheduler>

      <Grid data={gridData} rowRender={GridRowRender}>
        <GridColumn field="taskID" />
        <GridColumn field="title" />
      </Grid>
    </>
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));


问:
How can I simplify this javascript excerpt. In particular how do I set named object properties from an array
I would like to simplify this code fragment but can't get the syntax right to deconstruct an array into an object.</p>
```<code>let result = this.getSomething(x, y, z);
return { a: result[0], b: result[1] };
</code>```

Body:
I would like to simplify this code fragment but can't get the syntax right to deconstruct an array into an object.

let result = this.getSomething(x, y, z);
return { a: result[0], b: result[1] };


问:
How to provide CdvPurchase.Store in Angular
How can I setup cordova-plugin-purchase v13 with Angular 15?

This is what I have tried. Here is my PaymentService which is provided in root.

```<code>// payment.service.ts
import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import 'cordova-plugin-purchase';

@Injectable({
  providedIn: 'root'
})
export class PaymentService {

  constructor(
    private readonly store: CdvPurchase.Store,
    private readonly platform: Platform,
  ) {

    this.platform.ready().then((readySource) => {
      this.store.initialize();
    });
  }
}
</code>```

I'm providing the Store class in AppModule

```<code>// app.module.ts
import 'cordova-plugin-purchase';

@NgModule({
    // Omitting unrelevant parts
    providers: [
        {
            provide: CdvPurchase.Store,
            useFactory: () => { return window.CdvPurchase.Store }
        }
    ]
})
export class AppModule { }
</code>```

Firstly I'm getting this error in app.module.ts

```<code>Uncaught ReferenceError: CdvPurchase is not defined
</code>```

And down the line I'm getting this dependency injection error

```<code>ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(PaymentModule)[PaymentService -> PaymentService -> Store -> Store -> Store]:
  NullInjectorError: No provider for Store!
NullInjectorError: R3InjectorError(PaymentModule)[PaymentService -> PaymentService -> Store -> Store -> Store]:
</code>```

Thanks for the help.

Body:
How can I setup cordova-plugin-purchase v13 with Angular 15?

This is what I have tried. Here is my PaymentService which is provided in root.

// payment.service.ts
import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import 'cordova-plugin-purchase';

@Injectable({
  providedIn: 'root'
})
export class PaymentService {

  constructor(
    private readonly store: CdvPurchase.Store,
    private readonly platform: Platform,
  ) {

    this.platform.ready().then((readySource) => {
      this.store.initialize();
    });
  }
}

I'm providing the Store class in AppModule

// app.module.ts
import 'cordova-plugin-purchase';

@NgModule({
    // Omitting unrelevant parts
    providers: [
        {
            provide: CdvPurchase.Store,
            useFactory: () => { return window.CdvPurchase.Store }
        }
    ]
})
export class AppModule { }

Firstly I'm getting this error in app.module.ts

Uncaught ReferenceError: CdvPurchase is not defined

And down the line I'm getting this dependency injection error

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(PaymentModule)[PaymentService -> PaymentService -> Store -> Store -> Store]:
  NullInjectorError: No provider for Store!
NullInjectorError: R3InjectorError(PaymentModule)[PaymentService -> PaymentService -> Store -> Store -> Store]:

Thanks for the help.


问:
Unhandled Promise rejection : Timeout thrown with unit test and angular 14
I have recently upgraded our project to angular 14 where the tests were running fine before(around 4k tests in the project using jasmine/Karma)

I have upgraded Karma to 6.4.1 and Karma jasmine to 5.1.0. Now I seem to be getting random test failures (one run shows error in one component while the other run shows same error in the some other random component)

The errors are of the same format for the components:

The testName

```<code>    Unhandled Promise rejection : Timeout thrown
</code>```

All these tests have no promise rejections in the mocks and seem to be random
Has anyone across a similar issue?

Body:
I have recently upgraded our project to angular 14 where the tests were running fine before(around 4k tests in the project using jasmine/Karma)

I have upgraded Karma to 6.4.1 and Karma jasmine to 5.1.0. Now I seem to be getting random test failures (one run shows error in one component while the other run shows same error in the some other random component)

The errors are of the same format for the components:

The testName

    Unhandled Promise rejection : Timeout thrown

All these tests have no promise rejections in the mocks and seem to be random
Has anyone across a similar issue?


问:
The provided policy document does not meet the requirements of the specified policy type
I am getting an error while creating below SCP in AWS Organization.

Below is the error

The provided policy document does not meet the requirements of the specified policy type.

code

```<code>{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": " DenyEC2CreationSCP1",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/techops-system": "true"
          }
        }
      },
      {
        "Sid": "DenyEC2CreationSCP2",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/engineering-group": "true"
          }
        }
       },
        {
        "Sid": "DenyEC2CreationSCP3",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/environment": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP4",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/product": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP5",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/cost-type": "true"
          }
        }
        },
        {
        "Sid": " DenyEC2CreationSCP6",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/account": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP6",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/account-grouping": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP7",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/account-grouping": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP8",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/customer": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP8",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/Name": "true"
          }
        }
      }
    ]
  }
</code>```

I removed white spaces and validated syntax by YAML lint. All things are OK.

Body:
I am getting an error while creating below SCP in AWS Organization.

Below is the error

The provided policy document does not meet the requirements of the specified policy type.

code

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": " DenyEC2CreationSCP1",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/techops-system": "true"
          }
        }
      },
      {
        "Sid": "DenyEC2CreationSCP2",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/engineering-group": "true"
          }
        }
       },
        {
        "Sid": "DenyEC2CreationSCP3",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/environment": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP4",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/product": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP5",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/cost-type": "true"
          }
        }
        },
        {
        "Sid": " DenyEC2CreationSCP6",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/account": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP6",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/account-grouping": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP7",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/account-grouping": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP8",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/customer": "true"
          }
        }
        },
        {
        "Sid": "DenyEC2CreationSCP8",
        "Effect": "Deny",
        "Action": [
          "ec2:RunInstances"
        ],
        "Resource": [
          "arn:aws:ec2:*:*:instance/*",
          "arn:aws:ec2:*:*:volume/*",
          "arn:aws:ec2:*:*:elasticloadbalancing/*"
        ],
        "Condition": {
          "Null": {
            "aws:RequestTag/Name": "true"
          }
        }
      }
    ]
  }

I removed white spaces and validated syntax by YAML lint. All things are OK.


问:
How to do you load a model from a checkpoint using simple transformers?
I am using the simple transformers library, I have just finished training a model and now I want to load it to try making some predictions. However, I must be doing something wrong because it keeps raising an error. Here is my code:

```<code>from simpletransformers.seq2seq import Seq2SeqModel
model = Seq2SeqModel("marian","outputs/best_model")
print(model)

print(model.predict(["Using AI to Accelerate Scientific Discovery"]))

</code>```

Here is the error it displays:

```<code>ValueError: You must specify a Seq2Seq config    OR     encoder_type, encoder_name, and decoder_name OR                 encoder_type and encoder_decoder_name
</code>```

I have tried to search up answers from the documentation but I couldn't find anything.

Body:
I am using the simple transformers library, I have just finished training a model and now I want to load it to try making some predictions. However, I must be doing something wrong because it keeps raising an error. Here is my code:

from simpletransformers.seq2seq import Seq2SeqModel
model = Seq2SeqModel("marian","outputs/best_model")
print(model)

print(model.predict(["Using AI to Accelerate Scientific Discovery"]))

Here is the error it displays:

ValueError: You must specify a Seq2Seq config    OR     encoder_type, encoder_name, and decoder_name OR                 encoder_type and encoder_decoder_name

I have tried to search up answers from the documentation but I couldn't find anything.


问:
Dynamically address HTML elements with JavaScript, relative to the triggering object
I wrote a Responsive Website with HTML, CSS and JavaScript. On the desktop, the dropdown-menus in the menu are triggered via the CSS :hover event.
On the Mobile version, those menus collapse via a JavaScript event. I have two divs in the menu, which open dropdown-menus. With unique onclick events, a collapse class is added and removed to the items, via GetElementById.

HTML:

```<code><div class="dropdown-link" id="parentone">
        <!--link for the first parent menu-item-->
    <a class="menu-link" href="parent-one">Parent One</a>
        <!--div for the first dropdown-arrow-->
    <div class="dropdown-klick" id="parentonearrow" onclick="parentonedropdowntoggle()"></div>
        <!--div for the first dropdown-men-->
    <div class="dropdown-menu" id="parentonedropdown">
        <a class="menu-link" href="parent-one/item-one">Dropdown One Item</a>
        <a class="menu-link" href="parent-one/item-two">Dropdown One Item</a>
    </div>
</div>
</code>```

JavaScript:

```<code>//Code for toggling the adressed menu with unique events.
function parentonedropdowntoggle() {
  document.getElementById("parentone").classList.toggle("parentopen");
  document.getElementById("parentonearrow").classList.toggle("dropdownclose");
  document.getElementById("parentonedropdown").classList.toggle("dropdownopen");

//Code for closing the other dropdown-menu, when opened
  document.getElementById("parenttwo").classList.remove("dropdownclose");
  document.getElementById("parenttwoarrow").classList.remove("dropdownclose");
  document.getElementById("parenttwodropdown").classList.remove("dropdownopen");
}
</code>```

Both sections of code exist another time, to do the same actions for the second item in the menu, which has a dropdown. It does work for my site for now but obviously is extremely inflexible and not really usable, when a new one is added.

How can I use a single event, which assigns the class via JavaScript, to the div, that triggered the event?

I did not find any solution, when I searched my question on the internet. I was looking for something like this:

```<code>function dropdowntoggle() {
  document.getElementByTriggered("menu-link").classList.toggle("parentopen");
}
</code>```

A method, which would address the div with the class in the brackets, that triggered the above event. Am I on the right way, to achieve my goal?

Body:
I wrote a Responsive Website with HTML, CSS and JavaScript. On the desktop, the dropdown-menus in the menu are triggered via the CSS :hover event.
On the Mobile version, those menus collapse via a JavaScript event. I have two divs in the menu, which open dropdown-menus. With unique onclick events, a collapse class is added and removed to the items, via GetElementById.

HTML:

    Parent One

        Dropdown One Item
        Dropdown One Item

JavaScript:

//Code for toggling the adressed menu with unique events.
function parentonedropdowntoggle() {
  document.getElementById("parentone").classList.toggle("parentopen");
  document.getElementById("parentonearrow").classList.toggle("dropdownclose");
  document.getElementById("parentonedropdown").classList.toggle("dropdownopen");

//Code for closing the other dropdown-menu, when opened
  document.getElementById("parenttwo").classList.remove("dropdownclose");
  document.getElementById("parenttwoarrow").classList.remove("dropdownclose");
  document.getElementById("parenttwodropdown").classList.remove("dropdownopen");
}

Both sections of code exist another time, to do the same actions for the second item in the menu, which has a dropdown. It does work for my site for now but obviously is extremely inflexible and not really usable, when a new one is added.

How can I use a single event, which assigns the class via JavaScript, to the div, that triggered the event?

I did not find any solution, when I searched my question on the internet. I was looking for something like this:

function dropdowntoggle() {
  document.getElementByTriggered("menu-link").classList.toggle("parentopen");
}

A method, which would address the div with the class in the brackets, that triggered the above event. Am I on the right way, to achieve my goal?


问:
Assertion error when reading an excel file from the URL using Pandas
I am trying to read an excel directly from a URL using:

```<code>import pandas as pd

df = pd.read_excel('https://apps.fomento.gob.es/BoletinOnline2/sedal/34010110.XLS')

</code>```

However i get this error:

```<code>File "<ipython-input-153-d6607f341e37>", line 3, in <module>
    df = pd.read_excel('https://apps.fomento.gob.es/BoletinOnline2/sedal/34010110.XLS')

  File "D:\Anaconda\lib\site-packages\pandas\util\_decorators.py", line 299, in wrapper
    return func(*args, **kwargs)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_base.py", line 336, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_base.py", line 1131, in __init__
    self._reader = self._engines[engine](self._io, storage_options=storage_options)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_xlrd.py", line 25, in __init__
    super().__init__(filepath_or_buffer, storage_options=storage_options)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_base.py", line 391, in __init__
    self.book = self.load_workbook(self.handles.handle)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_xlrd.py", line 38, in load_workbook
    return open_workbook(file_contents=data)

  File "D:\Anaconda\lib\site-packages\xlrd\__init__.py", line 172, in open_workbook
    bk = open_workbook_xls(

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 104, in open_workbook_xls
    bk.parse_globals()

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 1213, in parse_globals
    self.handle_sst(data)

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 1180, in handle_sst
    self._sharedstrings, rt_runlist = unpack_SST_table(strlist, uniquestrings)

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 1476, in unpack_SST_table
    assert _unused_i == nstrings - 1

AssertionError
</code>```

I have also tried to read the excel of that URL by writing the content to an excel file and then reading it, but i get the same error:

```<code>import requests
import pandas as pd

req = requests.get('https://apps.fomento.gob.es/BoletinOnline2/sedal/34010110.XLS' )
url_content = req.content
open('my_file.xls', 'wb').write(url_content)
df = pd.read_excel('my_file.xls')
</code>```

After I open 'my_file.xls' with Office and save it from there, I can read it with Pandas as usual with 'df= pd.read_excel('my_file.xls')', but this happens with a lot of excels that I am trying to read so i can't go one by one saving them manually.

I don't know what could be happening. Thank you for your help.

Body:
I am trying to read an excel directly from a URL using:

import pandas as pd

df = pd.read_excel('https://apps.fomento.gob.es/BoletinOnline2/sedal/34010110.XLS')

However i get this error:

File "<ipython-input-153-d6607f341e37>", line 3, in <module>
    df = pd.read_excel('https://apps.fomento.gob.es/BoletinOnline2/sedal/34010110.XLS')

  File "D:\Anaconda\lib\site-packages\pandas\util\_decorators.py", line 299, in wrapper
    return func(*args, **kwargs)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_base.py", line 336, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_base.py", line 1131, in __init__
    self._reader = self._engines[engine](self._io, storage_options=storage_options)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_xlrd.py", line 25, in __init__
    super().__init__(filepath_or_buffer, storage_options=storage_options)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_base.py", line 391, in __init__
    self.book = self.load_workbook(self.handles.handle)

  File "D:\Anaconda\lib\site-packages\pandas\io\excel\_xlrd.py", line 38, in load_workbook
    return open_workbook(file_contents=data)

  File "D:\Anaconda\lib\site-packages\xlrd\__init__.py", line 172, in open_workbook
    bk = open_workbook_xls(

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 104, in open_workbook_xls
    bk.parse_globals()

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 1213, in parse_globals
    self.handle_sst(data)

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 1180, in handle_sst
    self._sharedstrings, rt_runlist = unpack_SST_table(strlist, uniquestrings)

  File "D:\Anaconda\lib\site-packages\xlrd\book.py", line 1476, in unpack_SST_table
    assert _unused_i == nstrings - 1

AssertionError

I have also tried to read the excel of that URL by writing the content to an excel file and then reading it, but i get the same error:

import requests
import pandas as pd

req = requests.get('https://apps.fomento.gob.es/BoletinOnline2/sedal/34010110.XLS' )
url_content = req.content
open('my_file.xls', 'wb').write(url_content)
df = pd.read_excel('my_file.xls')

After I open 'my_file.xls' with Office and save it from there, I can read it with Pandas as usual with 'df= pd.read_excel('my_file.xls')', but this happens with a lot of excels that I am trying to read so i can't go one by one saving them manually.

I don't know what could be happening. Thank you for your help.