问:
Executing a timeout prior to the defined delay
Say I have the following JavaScript code (in global context):

```<code>var t = setTimeout(f, a); // f is an arbitrary function, a an arbitrary timeout
</code>```

One can now cancel the set timeout:

```<code>clearTimeout(t);
</code>```

But is it also possible to execute the timeout prior to it normally firing?

E.g.:

```<code>var func = getFunctionFromTimeout(t); // Does a function like this exists?
clearTimeout(t);
func();
</code>```

or

```<code>executeAndClearTimeout(t); // Does this one?
</code>```

答:
No, that'ns ot possible.

However, you could write a wrapper for setTimeout and clearTimeout to achieve such a behaviour.

Body:
Say I have the following JavaScript code (in global context):

var t = setTimeout(f, a); // f is an arbitrary function, a an arbitrary timeout

One can now cancel the set timeout:

clearTimeout(t);

But is it also possible to execute the timeout prior to it normally firing?

E.g.:

var func = getFunctionFromTimeout(t); // Does a function like this exists?
clearTimeout(t);
func();

or

executeAndClearTimeout(t); // Does this one?


来源: stackexchange

问:
Azure Devops Query to find Daily hours spent on Work item
I have to find out time spend by a resource on a Task.

let say,

There are 3 Task (Task-A,Task-B,Task-C)

There are 3 User    (User-A,User-B,User-C)

All the Task have Original estimate of 8 hours

on Day 1 All the User have work 2 hours on their respective tasks

So I should get a result of 2

I am using Azure Work Item query to calculate and display the results.

I am not understanding what should be done to calculate the daily work done on a task.

答:
You can Analinics Views and Power BI. For example, you can add your custom view:

Then use it in Power BI:

ContentLicense: CC BY-SA 4.0


问:
how to list a range of numbers in file
I have a file named example.txt and inside the file I have numbers from 1 -50 but I only want to view number within a particular range like 1-25

I tried this command:
less example.txt | grep [1-25]

but this didn't help, please help

答:
IMHO the best way would be to use mathematical condition check rather than regex, please try following awk program.

```<code>awk '$0>=0 && $0<=25' Input_file
</code>```

Above will work if your lines are containing only digits eg:

```<code>1
2
3
.....
</code>```

In case your Input_file's lines can contain multiple digits that you want to print then better to loop through them and apply conditions to them and print them then.

```<code>awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}' Input_file
</code>```

Title: how to list a range of numbers in file

Body:
IMHO the best way would be to use mathematical condition check rather than regex, please try following awk program.

awk '$0>=0 && $0<=25' Input_file

Above will work if your lines are containing only digits eg:

1
2
3
.....

In case your Input_file's lines can contain multiple digits that you want to print then better to loop through them and apply conditions to them and print them then.

awk '{for(i=1;i<=NF;i++){if($i>=0 && $i<=25){print $i}}}' Input_file


问:
Python(Django): form write an ERROR befor submit
I want to check the Form after submit, but I have ERROR MASSAGE befor it.
I thing there is a mistake at VIEW-file

this is my views.py:

```<code>    @login_required
    def post_create(request):
        form = PostForm(request.POST)
        template = 'posts/create_post.html'
        if request.method == 'POST':
            if form.is_valid():
                form.instance.author = request.user
                form.save()
                return redirect('posts:profile', username=request.user.username)
        return render(request, template, {'form': form})
</code>```

this is my HTML template:

```<code>            {% if form.errors %}
                  {% for field in form %}
                    {% for error in field.errors %}
                      <div class="alert alert-danger">
                        {{ field.label }}: {{ error|escape }}
                      </div>
                    {% endfor %}
                  {% endfor %}
                  {% for error in form.non_field_errors %}
                    <div class="alert alert-danger">
                      {{ error|escape }}
                    </div>
                  {% endfor %}
              {% endif %}
</code>```

答:
your form is trying to submit when the page load. I usually prevent this using javascript.

try this:

```<code><script>
    form = document.getElementById('paymentform')
    form.addEventListener('submit', function(e){
        e.preventDefault(); // prevents the form from submitting on pageload
    form.submit();

    })
</script>
</code>```

first give your form an id, I gave mine paymentform and then paste the above code snippet at the bottom of your html file

Body:
I want to check the Form after submit, but I have ERROR MASSAGE befor it.
I thing there is a mistake at VIEW-file

this is my views.py:

    @login_required
    def post_create(request):
        form = PostForm(request.POST)
        template = 'posts/create_post.html'
        if request.method == 'POST':
            if form.is_valid():
                form.instance.author = request.user
                form.save()
                return redirect('posts:profile', username=request.user.username)
        return render(request, template, {'form': form})

this is my HTML template:

            {% if form.errors %}
                  {% for field in form %}
                    {% for error in field.errors %}

                        {{ field.label }}: {{ error|escape }}

                    {% endfor %}
                  {% endfor %}
                  {% for error in form.non_field_errors %}

                      {{ error|escape }}

                  {% endfor %}
              {% endif %}

Body:
your form is trying to submit when the page load. I usually prevent this using javascript.

try this:

<script>
    form = document.getElementById('paymentform')
    form.addEventListener('submit', function(e){
        e.preventDefault(); // prevents the form from submitting on pageload
    form.submit();

    })
</script>

first give your form an id, I gave mine paymentform and then paste the above code snippet at the bottom of your html file


问:
How can I intercept database requests(Peewee ORM) in pytest?
I have a main database and a replica (they are the same in the test environment):

```<code>core_db = PooledPostgresqlExtDatabase(**DB_COFIG)
replica_db = PooledPostgresqlExtDatabase(**DB_REPLICA_COFIG)
</code>```

A controllers that executes a query in different databases depending on the model

```<code>class BaseController:

    def _get_logs(self):
        query = self.model.select()
        if is_instance(self.model, ModelToReplica)
            query = query.bind(replica_db)
        return list(query)

class ReplicaExampleController(BaseLogsController):

    model = ModelToReplica

    def process(self):
        return self._get_logs()

class BaseExampleController(BaseLogsController):

    model = BaseModel

    def process(self):
        return self._get_logs()
</code>```

Controllers are linked to two urls:

```<code>/get_core_result/ # Returns the result from BaseExampleController (core_db)
/get_replica_result/ # Returns the result from ReplicaExampleController (replica_db)
</code>```

I want to check that each of the corners accesses the right base. And I know that the reference to the database object is stored in the request object. How do I get it from the test? I'm using a PyTest. I understand that I probably need to use mock, but I don't understand how.

Unfortunately, this is all I have so far:

```<code>class TestSwitchDB:

    def test_switch_db_to_replica():
        url_core = url_for('core_db_controller')
        core_result = self.client.get(url_core)

        url_replica = url_for('replica_db_controller')
        replica_result = self.client.get(url_replica)
</code>```

答:
In test_switch_db_to_replica you can mock the db query and patch it, something

```<code>with patch(BaseController._get_logs) as mock_get_logs:
    mock_get_logs.return_value="your expected return"
</code>```

As a reference: https://docs.python.org/3/library/unittest.mock-examples.html

Body:
I have a main database and a replica (they are the same in the test environment):

core_db = PooledPostgresqlExtDatabase(**DB_COFIG)
replica_db = PooledPostgresqlExtDatabase(**DB_REPLICA_COFIG)

A controllers that executes a query in different databases depending on the model

class BaseController:

    def _get_logs(self):
        query = self.model.select()
        if is_instance(self.model, ModelToReplica)
            query = query.bind(replica_db)
        return list(query)

class ReplicaExampleController(BaseLogsController):

    model = ModelToReplica

    def process(self):
        return self._get_logs()

class BaseExampleController(BaseLogsController):

    model = BaseModel

    def process(self):
        return self._get_logs()

Controllers are linked to two urls:

/get_core_result/ # Returns the result from BaseExampleController (core_db)
/get_replica_result/ # Returns the result from ReplicaExampleController (replica_db)

I want to check that each of the corners accesses the right base. And I know that the reference to the database object is stored in the request object. How do I get it from the test? I'm using a PyTest. I understand that I probably need to use mock, but I don't understand how.

Unfortunately, this is all I have so far:

class TestSwitchDB:

    def test_switch_db_to_replica():
        url_core = url_for('core_db_controller')
        core_result = self.client.get(url_core)

        url_replica = url_for('replica_db_controller')
        replica_result = self.client.get(url_replica)

Body:
In test_switch_db_to_replica you can mock the db query and patch it, something

with patch(BaseController._get_logs) as mock_get_logs:
    mock_get_logs.return_value="your expected return"

As a reference: https://docs.python.org/3/library/unittest.mock-examples.html


问:
Find columns where week row and year row matches values given in another cell range
I have a matrix in excel where the 2 top rows are "Year" and "Week".

As you probably could imagine there is a lot of columns in this matrix as time goes by. Therefore I would like a button that simply sends the user to the column with year and week matching the 2 "search cells"

To illustrate:

What I want is just to select the column or Year-Week range that matches the criterias in cell B1 and B2.

So that it would select column C or range("C4:C5") with the criterias given in the picture.

I simply cant wrap my head around it atm, so I hope you can help me.

Thanks in advance!

答:
You can use COUNTIF first to check if the value exist and then EVALUATE to get column number and select

```<code>Sub test()
Dim ThisColumn As Integer

'first, check that year and week exists
If Application.WorksheetFunction.CountIfs(Range("A4:G4"), Range("B1"), Range("A5:G5"), Range("B2")) = 0 Then
    'not found
    MsgBox "Year and week not found", vbCritical, "ERROR"
Else
    'found, then select
    ThisColumn = Evaluate("=MATCH(B1&B2,TRANSPOSE(A4:G4)&TRANSPOSE(A5:G5),0)")
    Range(Cells(4, ThisColumn), Cells(5, ThisColumn)).Select
End If

End Sub
</code>```

If you put a year and or a week not found, then it will raise an error:

Please, note that you'll need to adapt the ranges in case you have more values at rows 4 and 5

Body:
You can use COUNTIF first to check if the value exist and then EVALUATE to get column number and select

Sub test()
Dim ThisColumn As Integer

'first, check that year and week exists
If Application.WorksheetFunction.CountIfs(Range("A4:G4"), Range("B1"), Range("A5:G5"), Range("B2")) = 0 Then
    'not found
    MsgBox "Year and week not found", vbCritical, "ERROR"
Else
    'found, then select
    ThisColumn = Evaluate("=MATCH(B1&B2,TRANSPOSE(A4:G4)&TRANSPOSE(A5:G5),0)")
    Range(Cells(4, ThisColumn), Cells(5, ThisColumn)).Select
End If

End Sub

If you put a year and or a week not found, then it will raise an error:

Please, note that you'll need to adapt the ranges in case you have more values at rows 4 and 5


问:
Make a specific query based on the chosen radio value
I have a form like this:

```<code><form>
    <input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/>
    <button type="submit" id="findWord" class="btn btn-primary">Search</button>

    <div>
      <input type="radio" value="exact match" id="exact-match">
      <label for="exact-match" class="checked" checked>Exact match</label>
      <input type="radio"  value="all matches" id="all-matches">
      <label for="all-matches">All matches</label>
    </div>
  </form>
</code>```

Because I can't use name="" for radio buttons in this project, I made a script to toggle them using a class.

```<code>    let radioBtns = document.querySelectorAll('input[type="radio"]');

    function toggleCheck() {
      radioBtns.forEach(function (radioBtn) {
        radioBtn.classList.toggle('checked');
        radioBtn.classList.contains('checked') ? radioBtn.checked = true : radioBtn.checked = false;
     });
    }

    radioBtns.forEach(function (radioBtn){
    radioBtn.addEventListener('click', toggleCheck, false);
    });

    let anyMatch = document.getElementById('all-matches').classList.contains('checked');
    console.log(anyMatch);
    let exactMatch = document.getElementById('exact-match').classList.contains('checked');
    console.log(exactMatch);
</code>```

Based on the chosen radio, I have to do a different query.
If I choose exact match, the word(s) from input will contain quotes (queryWithQuotes).
If I choose all matches, the words from input don't contain the quotes (queryWithoutQuotes).

```<code>        let pageUrl = window.location.protocol + "//" + window.location.host;
        const searchTerm = document.getElementById("searchedWord").value.replace("'", "''");

        if (exactMatch === true) {
            let queryWithQuotes = pageUrl  + "/_api/search/query?querytext='" + '"' + searchTerm + '"' + "'&selectproperties='Path%2cUrl'&sourceid='xxxxx'";
            console.log(`queryWithQuotes variable is: ${queryWithQuotes }`);
            $.ajax(
                {
                    url: queryWithQuotes,
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: success,
                    error: error
                }
            );
        } else if (anyMatch === true) {
            let queryWithoutQuotes = pageUrl  + "/_api/search/query?querytext='" + searchTerm + "'&selectproperties='Path%2cUrl'&sourceid='xxxxx'";
            console.log(`queryWithoutQuotes variable is: ${queryWithoutQuotes }`);
            $.ajax(
                {
                    url: queryWithoutQuotes,
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: success,
                    error: error
                }
            );
        } else {
            console.log('There is an error');
        }
</code>```

For some reasons, the search is taking into consideration only the exact match. Even if I switch to All matches, search will continue with Exact match.

What is the reason?

答:
I cleaned up the code and this works fine in jsfiddle and SO code snippet. I don't know if you left important stuff out but maybe this'll help out in better understanding where your problems are coming from. I've commented all the changes I've made; feel free to ignore any that are just a result of posting here.

  let radioBtns = document.querySelectorAll('input[type="radio"]');

  function toggleCheck() {
    radioBtns.forEach(function (radioBtn) {
      radioBtn.classList.toggle('checked');
      radioBtn.checked = radioBtn.classList.contains('checked') ? true : false; // I fixed this ternary operator.
    });
  }

  radioBtns.forEach(function (radioBtn){
    radioBtn.addEventListener('click', toggleCheck, false);
  });

  function doSearch() {
    // I suspect this is the key issue that you had. The checks for anyMatch and exactMatch need to be inside the function for them to update.
    let anyMatch = document.getElementById('all-matches').classList.contains('checked');
    let exactMatch = document.getElementById('exact-match').classList.contains('checked');

    console.log('exact match:', exactMatch, '; any match:', anyMatch);

    // ... do the actual code here where you check anyMatch and exactMatch
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/>
<button type="button" onclick="doSearch()" id="findWord" class="btn btn-primary">Search</button> <!-- I changed this button from submit to regular button since you're handling everything in javascript anyway -->

<div>
  <input type="radio" value="exact match" id="exact-match" class="checked" checked> <!-- I gave one of the radio buttons a "checked" by default -->
  <label for="exact-match" class="checked" checked>Exact match</label>
  <input type="radio"  value="all matches" id="all-matches">
  <label for="all-matches">All matches</label>
</div></code>```

Body:
I have a form like this:

<form>
    <input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/>
    <button type="submit" id="findWord" class="btn btn-primary">Search</button>

      <input type="radio" value="exact match" id="exact-match">
      Exact match
      <input type="radio"  value="all matches" id="all-matches">
      All matches

  </form>

Because I can't use name="" for radio buttons in this project, I made a script to toggle them using a class.

    let radioBtns = document.querySelectorAll('input[type="radio"]');

    function toggleCheck() {
      radioBtns.forEach(function (radioBtn) {
        radioBtn.classList.toggle('checked');
        radioBtn.classList.contains('checked') ? radioBtn.checked = true : radioBtn.checked = false;
     });
    }

    radioBtns.forEach(function (radioBtn){
    radioBtn.addEventListener('click', toggleCheck, false);
    });

    let anyMatch = document.getElementById('all-matches').classList.contains('checked');
    console.log(anyMatch);
    let exactMatch = document.getElementById('exact-match').classList.contains('checked');
    console.log(exactMatch);

Based on the chosen radio, I have to do a different query.
If I choose exact match, the word(s) from input will contain quotes (queryWithQuotes).
If I choose all matches, the words from input don't contain the quotes (queryWithoutQuotes).

        let pageUrl = window.location.protocol + "//" + window.location.host;
        const searchTerm = document.getElementById("searchedWord").value.replace("'", "''");

        if (exactMatch === true) {
            let queryWithQuotes = pageUrl  + "/_api/search/query?querytext='" + '"' + searchTerm + '"' + "'&selectproperties='Path%2cUrl'&sourceid='xxxxx'";
            console.log(`queryWithQuotes variable is: ${queryWithQuotes }`);
            $.ajax(
                {
                    url: queryWithQuotes,
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: success,
                    error: error
                }
            );
        } else if (anyMatch === true) {
            let queryWithoutQuotes = pageUrl  + "/_api/search/query?querytext='" + searchTerm + "'&selectproperties='Path%2cUrl'&sourceid='xxxxx'";
            console.log(`queryWithoutQuotes variable is: ${queryWithoutQuotes }`);
            $.ajax(
                {
                    url: queryWithoutQuotes,
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: success,
                    error: error
                }
            );
        } else {
            console.log('There is an error');
        }

For some reasons, the search is taking into consideration only the exact match. Even if I switch to All matches, search will continue with Exact match.

What is the reason?

Body:
I cleaned up the code and this works fine in jsfiddle and SO code snippet. I don't know if you left important stuff out but maybe this'll help out in better understanding where your problems are coming from. I've commented all the changes I've made; feel free to ignore any that are just a result of posting here.

  let radioBtns = document.querySelectorAll('input[type="radio"]');

  function toggleCheck() {
    radioBtns.forEach(function (radioBtn) {
      radioBtn.classList.toggle('checked');
      radioBtn.checked = radioBtn.classList.contains('checked') ? true : false; // I fixed this ternary operator.
    });
  }

  radioBtns.forEach(function (radioBtn){
    radioBtn.addEventListener('click', toggleCheck, false);
  });

  function doSearch() {
    // I suspect this is the key issue that you had. The checks for anyMatch and exactMatch need to be inside the function for them to update.
    let anyMatch = document.getElementById('all-matches').classList.contains('checked');
    let exactMatch = document.getElementById('exact-match').classList.contains('checked');

    console.log('exact match:', exactMatch, '; any match:', anyMatch);

    // ... do the actual code here where you check anyMatch and exactMatch
  }

<input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/>
<button type="button" onclick="doSearch()" id="findWord" class="btn btn-primary">Search</button> <!-- I changed this button from submit to regular button since you're handling everything in javascript anyway -->

<div>
  <input type="radio" value="exact match" id="exact-match" class="checked" checked> <!-- I gave one of the radio buttons a "checked" by default -->
  <label for="exact-match" class="checked" checked>Exact match</label>
  <input type="radio"  value="all matches" id="all-matches">
  <label for="all-matches">All matches</label>
</div>


问:
EF6 stored procedure - output direction parameter
What's the right way to run a EF6 stored procedure with output direction parameter?

```<code>List<MySqlParameter> parms = new()
{
   new MySqlParameter { ParameterName = "@FilterJson", Value = JsonConvert.SerializeObject(input) },
   new MySqlParameter { ParameterName = "@OutputJson", Direction = System.Data.ParameterDirection.Output }
};

var response = ReportingDetail.FromSqlRaw(
   @"CALL p_detail_get(@FilterJson, @OutputJson)",
   parms.ToArray()
);
</code>```

This code throws an error:

MySqlConnector.MySqlException: 'Only ParameterDirection.Input is supported when CommandType is Text (parameter name: @OutputJson)'

Expected output is JSON, something like:
{"rows_count": 7, "actual_page": 1, "pages_count": 1}

The problem is not with a connection, other procedures with no output direction works fine. Defining a type of @OutputJson does not fix the issue - MySqlDbType = MySqlDbType.JSON or DbType = System.Data.DbType.Object.

Thank you for any help

答: According to the MySqlConnector disscussion, it is not possible to return output direction parameters through it. You can try to write ADO.NET code to omit this restriction.</p>

Body:
What's the right way to run a EF6 stored procedure with output direction parameter?

List<MySqlParameter> parms = new()
{
   new MySqlParameter { ParameterName = "@FilterJson", Value = JsonConvert.SerializeObject(input) },
   new MySqlParameter { ParameterName = "@OutputJson", Direction = System.Data.ParameterDirection.Output }
};

var response = ReportingDetail.FromSqlRaw(
   @"CALL p_detail_get(@FilterJson, @OutputJson)",
   parms.ToArray()
);

This code throws an error:

MySqlConnector.MySqlException: 'Only ParameterDirection.Input is supported when CommandType is Text (parameter name: @OutputJson)'

Expected output is JSON, something like:
{"rows_count": 7, "actual_page": 1, "pages_count": 1}

The problem is not with a connection, other procedures with no output direction works fine. Defining a type of @OutputJson does not fix the issue - MySqlDbType = MySqlDbType.JSON or DbType = System.Data.DbType.Object.

Thank you for any help


问:
How to pass variables to the ansible provisioner in Packer?
When using vanilla Ansible playbooks, I have a number of inventories that encapsulate various configurations via the setting of variables; these work as expected. I now wish to use one or more playbooks from the Packer Ansible plugin to perform the same steps.

At present, I have resorted to passing arguments via the "--extra-vars" directive; for a limited number of variables, this is acceptable. However, I would prefer to be able to reference the existing inventory file which contains the set of variables I wish to use.

Is this possible?

答:
Yes, you can specify the inventory file containing the variables in the Packer Ansible provisioner:

```<code>provisioner "ansible" {
  inventory_file = "${path.root}/path/to/inventory"
}
</code>```

More information is available in the documentation.

However, this can also become tricky since Packer normally generates an inventory file with an entry for the instance being provisioned. You may have difficulties adapting the host entry for the instance being provisioned to the existing inventory file. It may be easier to use the inventory directory instead:

```<code>provisioner "ansible" {
  inventory_directory = "${path.root}/path/to/inventory_dir"
}
</code>```

In that situation, Packer will still generate the guaranteed accurate inventory file for you, but host_vars and group_vars from the existing inventory files will still be available from the directory.

Body:
Yes, you can specify the inventory file containing the variables in the Packer Ansible provisioner:

provisioner "ansible" {
  inventory_file = "${path.root}/path/to/inventory"
}

More information is available in the documentation.

However, this can also become tricky since Packer normally generates an inventory file with an entry for the instance being provisioned. You may have difficulties adapting the host entry for the instance being provisioned to the existing inventory file. It may be easier to use the inventory directory instead:

provisioner "ansible" {
  inventory_directory = "${path.root}/path/to/inventory_dir"
}

In that situation, Packer will still generate the guaranteed accurate inventory file for you, but host_vars and group_vars from the existing inventory files will still be available from the directory.


问:
React useEffect behavior
Having such a simple React component:

```<code>import React, { FunctionComponent, useEffect, useState } from 'react';

export function useMediaQuery(query:string) {

    console.log("useMediaQuery")

    useEffect(() => {
        console.log("useEffect outer")
        // ...
    });

}

const Sidebar: FunctionComponent = () => {

    const istoBeHidden = useMediaQuery('(min-width: 700px)')
    console.log("returned from useMediaQuery")
    useEffect(() => console.log("useEffect inner"))

    return (
        <div>
            <p>Sidebar</p>
            {/* <button onClick={myFunction}>Click me</button> */}
        </div>
    )
};

export {Sidebar}
</code>```

I'm getting the following output in the console:

useMediaQuery

returned from useMediaQuery

useEffect outer

useEffect inner

My question is WHY does the useEffect outer is called AFTER returning from the
useMediaQuery function (why does the line useEffect outer appears AFTER the line returned from useMediaQuery)!?

答:
We need a little bit of a background here to understand why it behaves like this.

As we all know React uses JSX, which produces a representation of DOM. It means all functions get called to produce it each time React decides to update. After that, another step takes place and all effects get evaluated. Effects are guaranteed to run after rendering.

Now, going back to your case.
In first phase, React calls your Sidebar function. All functions inside of it get executed, therefore you see logs in your console. After that, changes are committed and effects are called. That's why you see logs from the effects at the end.

Title: React useEffect behavior

Body:
Having such a simple React component:

import React, { FunctionComponent, useEffect, useState } from 'react';

export function useMediaQuery(query:string) {

    console.log("useMediaQuery")

    useEffect(() => {
        console.log("useEffect outer")
        // ...
    });

}

const Sidebar: FunctionComponent = () => {

    const istoBeHidden = useMediaQuery('(min-width: 700px)')
    console.log("returned from useMediaQuery")
    useEffect(() => console.log("useEffect inner"))

    return (

Sidebar

            {/* <button onClick={myFunction}>Click me</button> */}

    )
};

export {Sidebar}

I'm getting the following output in the console:

useMediaQuery

returned from useMediaQuery

useEffect outer

useEffect inner

My question is WHY does the useEffect outer is called AFTER returning from the
useMediaQuery function (why does the line useEffect outer appears AFTER the line returned from useMediaQuery)!?


问:
Grant Create Sequence in PostgreSQL
Is it possible to grant a user/role only the permission to create/alter sequences in a PostgreSQL database/schema not allowing the user to create tables at the same time?

I currently use

GRANT CREATE ON SCHEMA myschema TO "MyRole";

which gives the user full create access to the schema, though he cannot delete or alter any tables that he does not own. My use case is that I use Liquibase to setup the database schema upfront and want to have the application only using a db user that can only read/write data. Unfortunately the application requires a dynamic number of sequences, i.e. it must be possible for the application to create new sequences in the database/schema.

答:
You can do

```<code>grant select on sequence my_sequence in schema my_schema to my_role_user
</code>```

https://www.postgresql.org/docs/14/sql-grant.html

Title: Grant Create Sequence in PostgreSQL

Body:
You can do

grant select on sequence my_sequence in schema my_schema to my_role_user

https://www.postgresql.org/docs/14/sql-grant.html


问:
Initiate BIM360 Docs collaboration programmatically
In order to upgrade to the current version of Revit, we have to migrate our files from from BIM360 Teams to BIM360 Docs. Since we have hundreds of documents, I am looking to automate this process as much as possible.

The forge API allows me to download all Revit files from BIM360 Teams. I am also able to upgrade them all to Revit 2019, using either the Revit API or a third party app such as this Bulk File Upgrader`.

Using the Forge BIM360 API, I am able to create new projects programmatically, and upload the files and folders from the Team Drive. The step that I am having difficulty accomplishing in an automated fashion is to initiate collaboration for the upgraded Revit 2019 files. Is there a way that this can be accomplished with either the Revit API or the Forge API? Or is there another way that allows me to automatically accomplish the migration between these two Autodesk Cloud Collaboration solutions?

I came across this tutorial on publishing models, which suggests that one needs to manually initiate collaboration for each Revit file through the Revit UI. I hope to find an alternative solution to this suggestion.

Thank you!

答:
Autodesk has also recently published a GitHub repository with a solution for this exact scenario. You can find the video here which talk about this. This basically uses enhanced api calls in Revit 2022 API - RevitLinkType.Create & RevitLinkType.LoadFrom which support cloud model creation and linking.

There's a related question about how to create new cloud models using Revit API.


问:
How to test a Spring CommandLineRunner while I am mocking the connection to an external resources?
I want to test the following class, that is a spring boot with CommandLineRunner, if it receives the flag compaction.manually.triggered = true for specific TaskMode. I suppose that I need to instantiate the whole Spring application runner during the test (based on this answer). However, I don't want to connect to external resources (was in my case). So I think I need to mock it as well.

```<code>@Component
public class MyRunner implements CommandLineRunner {
    private final MyTask myTask;
    private final CompactionMode mode;
    private final boolean manuallyTriggered;

    @Autowired
    public MyRunner(
        MyTask myTask,
        @Value("${task.mode}") TaskMode mode,
        @Value("#{new Boolean('${compaction.manually.triggered:false}')}") boolean manuallyTriggered
    ) {
        Preconditions.checkNotNull(mode, "Compaction mode was not specified correctly");
        this.mode = mode;
        this.manuallyTriggered = manuallyTriggered;
        this.myTask = myTask;
    }

    @Override
    public void run(final String... args) {
        try {
            Preconditions.checkNotNull(mode, "Compaction mode was not specified correctly");
            LOG.info(
                "Task reporting compactor in {} mode started. The task was triggered {}.",
                mode,
                manuallyTriggered ? "manually" : "by the conJob schedule"
            );
            switch (mode) {
                case KPI, ANALYTICS, ANALYTICS_AGG -> {
                    checkManuallyTriggered(mode);
                    myTask.executeTask();
                }
                default -> throw new UnsupportedOperationException("myTask mode " + mode + " is not supported.");
            }
            System.exit(0);
        } catch (Exception ex) {
            LOG.error("Failure during mytask in {} mode", mode, ex);
            System.exit(-1);
        }
    }
    private void checkManuallyTriggered(CompactionMode mode) {
        if (!manuallyTriggered) {
            throw new UnsupportedOperationException(
                "Reporting compactor mode " + mode.name() + " is supported only using the " + "parameter --compaction.manually.triggered=true.");
        }
    }
}
</code>```

I wrote the test below and my commandLineRunner is Null when I use @ExtendWith(MockitoExtension.class). I understand that I cannot use @ExtendWith(MockitoExtension.class) and want that Spring initializes my context. So I tried to switch to @SpringBootTest. Then spring initializes my context but it tries to connect to AWS. So, I don't know to mock the connection to AWS while using @SpringBootTest to initialize the spring context during test.

```<code>// @SpringBootTest // ENABLE THIS TO TEST THE CommandLineRunner
@ExtendWith(MockitoExtension.class) // ENABLE THIS TO MOCK THE SERVICES CONNECTION TO AWS
class ReportingCompactorRunnerTest {

    AthenaProperties athenaProperties = new AthenaProperties(
        "com.simba.athena.jdbc42.Driver",
        "eu-central-1",
        "database",
        "test_reports"
    );
    private AthenaDirectConnection athenaDirectConnection = mock(AthenaDirectConnection.class, Mockito.RETURNS_DEEP_STUBS);
    private MockSettings mockSettings = withSettings().useConstructor(athenaDirectConnection, athenaProperties);
    private AthenaImportDDLService athenaImportDDLService = mock(AthenaImportDDLService.class, mockSettings);
    @Mock
    private MyTask myTask;
    @SpyBean // using this annotation to spy the arguments on the CommandLineRunner
    private ReportingCompactorRunner commandLineRunner;

    @DynamicPropertySource
    static void containerProperties(DynamicPropertyRegistry registry) {
        registry.add("compaction.mode", () -> "KPI");
        registry.add("compaction.manually.triggered", () -> "false");
    }
    @Test
    void analyticsCleanupIsTriggeredOnlyManually() throws Exception {
        doNothing().when(myTask).createViewsIfNotExist(); // a call inside the task that I don't want to execute

        // commandLineRunner IS NULL WHEN I USE MOCKITO
        RuntimeException thrown = assertThrows(
            RuntimeException.class,
            () -> commandLineRunner.run()
        );

        // assertTrue(thrown.getMessage().contains("Reporting compactor mode ANALYTICS_CLEANUP is supported only
        // using the parameter --compaction.manually.triggered=true."));
        assertTrue(thrown.getMessage().contains("null"));
        verify(athenaReportCompactionTask, times(1)).executeTask();
    }
}
</code>```

答:
As @M. Deinum said, it is not necessary to start the Spring context to test what I wanted. I will post the solution here just as a reference. I am also using the system-lambda dependency to catch System.exit(-1).

```<code><dependency>
   <groupId>com.github.stefanbirkner</groupId>
   <artifactId>system-lambda</artifactId>
</dependency>
</code>```

Unit test with only Mockito:

```<code>@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MyRunnerTest {

    private AthenaImportDDLService athenaImportDDLService;
    @Mock
    private MyTask1 myTask;
    private MyRunner commandLineRunner;

    private static Stream<Arguments> compactionModeAndTriggeredFlagParameters() {
        return Stream.of(
            Arguments.of(CompactionMode.KPI, true, 0),
            Arguments.of(CompactionMode.KPI, false, 0),
            ....
        );
    }

    @BeforeAll
    public void setup() {
        AthenaProperties athenaProperties = new AthenaProperties("com.simba.athena.jdbc42.Driver","eu-central-1","database","test_reports");
        AthenaDirectConnection athenaDirectConnection = mock(AthenaDirectConnection.class, Mockito.RETURNS_DEEP_STUBS);
        MockSettings mockSettings = withSettings().useConstructor(athenaDirectConnection, athenaProperties);
        athenaImportDDLService = mock(AthenaImportDDLService.class, mockSettings);
    }

    @ParameterizedTest
    @MethodSource("compactionModeAndTriggeredFlagParameters")
    void compactionModesWithManuallyTriggeredFlag(CompactionMode mode, boolean manuallyTriggered, int expectedCode)
    throws Exception {
        doNothing().when(athenaImportDDLService).createViewsIfNotExist();
        commandLineRunner = new MyRunner(
            myTask,
            mode,
            manuallyTriggered
        );
        int statusCode = catchSystemExit(() -> {
            commandLineRunner.run();
        });
        assertEquals(expectedCode, statusCode);
    }
}
</code>```

Body:
I want to test the following class, that is a spring boot with CommandLineRunner, if it receives the flag compaction.manually.triggered = true for specific TaskMode. I suppose that I need to instantiate the whole Spring application runner during the test (based on this answer). However, I don't want to connect to external resources (was in my case). So I think I need to mock it as well.

@Component
public class MyRunner implements CommandLineRunner {
    private final MyTask myTask;
    private final CompactionMode mode;
    private final boolean manuallyTriggered;

    @Autowired
    public MyRunner(
        MyTask myTask,
        @Value("${task.mode}") TaskMode mode,
        @Value("#{new Boolean('${compaction.manually.triggered:false}')}") boolean manuallyTriggered
    ) {
        Preconditions.checkNotNull(mode, "Compaction mode was not specified correctly");
        this.mode = mode;
        this.manuallyTriggered = manuallyTriggered;
        this.myTask = myTask;
    }

    @Override
    public void run(final String... args) {
        try {
            Preconditions.checkNotNull(mode, "Compaction mode was not specified correctly");
            LOG.info(
                "Task reporting compactor in {} mode started. The task was triggered {}.",
                mode,
                manuallyTriggered ? "manually" : "by the conJob schedule"
            );
            switch (mode) {
                case KPI, ANALYTICS, ANALYTICS_AGG -> {
                    checkManuallyTriggered(mode);
                    myTask.executeTask();
                }
                default -> throw new UnsupportedOperationException("myTask mode " + mode + " is not supported.");
            }
            System.exit(0);
        } catch (Exception ex) {
            LOG.error("Failure during mytask in {} mode", mode, ex);
            System.exit(-1);
        }
    }
    private void checkManuallyTriggered(CompactionMode mode) {
        if (!manuallyTriggered) {
            throw new UnsupportedOperationException(
                "Reporting compactor mode " + mode.name() + " is supported only using the " + "parameter --compaction.manually.triggered=true.");
        }
    }
}

I wrote the test below and my commandLineRunner is Null when I use @ExtendWith(MockitoExtension.class). I understand that I cannot use @ExtendWith(MockitoExtension.class) and want that Spring initializes my context. So I tried to switch to @SpringBootTest. Then spring initializes my context but it tries to connect to AWS. So, I don't know to mock the connection to AWS while using @SpringBootTest to initialize the spring context during test.

// @SpringBootTest // ENABLE THIS TO TEST THE CommandLineRunner
@ExtendWith(MockitoExtension.class) // ENABLE THIS TO MOCK THE SERVICES CONNECTION TO AWS
class ReportingCompactorRunnerTest {

    AthenaProperties athenaProperties = new AthenaProperties(
        "com.simba.athena.jdbc42.Driver",
        "eu-central-1",
        "database",
        "test_reports"
    );
    private AthenaDirectConnection athenaDirectConnection = mock(AthenaDirectConnection.class, Mockito.RETURNS_DEEP_STUBS);
    private MockSettings mockSettings = withSettings().useConstructor(athenaDirectConnection, athenaProperties);
    private AthenaImportDDLService athenaImportDDLService = mock(AthenaImportDDLService.class, mockSettings);
    @Mock
    private MyTask myTask;
    @SpyBean // using this annotation to spy the arguments on the CommandLineRunner
    private ReportingCompactorRunner commandLineRunner;

    @DynamicPropertySource
    static void containerProperties(DynamicPropertyRegistry registry) {
        registry.add("compaction.mode", () -> "KPI");
        registry.add("compaction.manually.triggered", () -> "false");
    }
    @Test
    void analyticsCleanupIsTriggeredOnlyManually() throws Exception {
        doNothing().when(myTask).createViewsIfNotExist(); // a call inside the task that I don't want to execute

        // commandLineRunner IS NULL WHEN I USE MOCKITO
        RuntimeException thrown = assertThrows(
            RuntimeException.class,
            () -> commandLineRunner.run()
        );

        // assertTrue(thrown.getMessage().contains("Reporting compactor mode ANALYTICS_CLEANUP is supported only
        // using the parameter --compaction.manually.triggered=true."));
        assertTrue(thrown.getMessage().contains("null"));
        verify(athenaReportCompactionTask, times(1)).executeTask();
    }
}

Body:
As @M. Deinum said, it is not necessary to start the Spring context to test what I wanted. I will post the solution here just as a reference. I am also using the system-lambda dependency to catch System.exit(-1).

<dependency>
   <groupId>com.github.stefanbirkner</groupId>
   <artifactId>system-lambda</artifactId>
</dependency>

Unit test with only Mockito:

@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MyRunnerTest {

    private AthenaImportDDLService athenaImportDDLService;
    @Mock
    private MyTask1 myTask;
    private MyRunner commandLineRunner;

    private static Stream<Arguments> compactionModeAndTriggeredFlagParameters() {
        return Stream.of(
            Arguments.of(CompactionMode.KPI, true, 0),
            Arguments.of(CompactionMode.KPI, false, 0),
            ....
        );
    }

    @BeforeAll
    public void setup() {
        AthenaProperties athenaProperties = new AthenaProperties("com.simba.athena.jdbc42.Driver","eu-central-1","database","test_reports");
        AthenaDirectConnection athenaDirectConnection = mock(AthenaDirectConnection.class, Mockito.RETURNS_DEEP_STUBS);
        MockSettings mockSettings = withSettings().useConstructor(athenaDirectConnection, athenaProperties);
        athenaImportDDLService = mock(AthenaImportDDLService.class, mockSettings);
    }

    @ParameterizedTest
    @MethodSource("compactionModeAndTriggeredFlagParameters")
    void compactionModesWithManuallyTriggeredFlag(CompactionMode mode, boolean manuallyTriggered, int expectedCode)
    throws Exception {
        doNothing().when(athenaImportDDLService).createViewsIfNotExist();
        commandLineRunner = new MyRunner(
            myTask,
            mode,
            manuallyTriggered
        );
        int statusCode = catchSystemExit(() -> {
            commandLineRunner.run();
        });
        assertEquals(expectedCode, statusCode);
    }
}


问:
upload and translate object using Autodesk forge tutorial
A couple of days ago, I started learning Autodesk Forge using their tutorial, and it worked just fine till show on viewer step.

Today, when I run my app, the browser opens, however, I can not upload or translate an object(file) in the bucket.

the picture simply shows the buckets I've created and the uploaded files. Only .rfa and cannot even translate them

Please check this simple recording for my issue, the video simply shows that I cannot upload the .rvt file

答: I had this similar issue where I was able to upload files to the OSS, however was unable to translate in order for the models to be viewable in the viewer. My solution was to use an active Autodesk Forge account as I found out that my free trial had expired.</p>


问:
AzureML: Dataset Profile fails when parquet file is empty
I have created a Tabular Dataset using Azure ML python API. Data under question is a bunch of parquet files (~10K parquet files each of size of 330 KB) residing in Azure Data Lake Gen 2 spread across multiple partitions. When I trigger "Generate Profile" operation for the dataset, it throws following error while handling empty parquet file and then the profile generation stops.

```<code>User program failed with ExecutionError:
Error Code: ScriptExecution.StreamAccess.Validation
Validation Error Code: NotSupported
Validation Target: ParquetFile
Failed Step: 77866d0a-8243-4d3d-8bc6-599d466488dd
Error Message: ScriptExecutionException was caused by StreamAccessException.
  Failed to read Parquet file at: <my_blob_path>/20211217.parquet
    Current parquet file is not supported.
      Exception of type 'Thrift.Protocol.TProtocolException' was thrown.
| session_id=6be4db0b-bdc1-4dd6-b8a6-6e9466f7bc54

</code>```

By empty parquet file, I mean that the if I read the individual parquet file using pandas (pd.read_parquet), it results in an empty DF (df.empty == True).

Any suggestion to avoid this error will be appreciated.

Update
The issue has been fixed in the following version:

azureml-dataprep : 3.0.1

azureml-core :  1.40.0

答:
```<code>Error Code: ScriptExecution.StreamAccess.Validation
</code>```

Above error is caused because you are not able to access ADLS.

You can create Azure App Identity and assign read access to ADLS. Now register ADLS as a datastore in workspace using client id and secret of app identity. After these steps your code will be able to access datastore.

Refer - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-network-security-overview#configure-a-datastore-to-use-managed-identity

Body:
I have created a Tabular Dataset using Azure ML python API. Data under question is a bunch of parquet files (~10K parquet files each of size of 330 KB) residing in Azure Data Lake Gen 2 spread across multiple partitions. When I trigger "Generate Profile" operation for the dataset, it throws following error while handling empty parquet file and then the profile generation stops.

User program failed with ExecutionError:
Error Code: ScriptExecution.StreamAccess.Validation
Validation Error Code: NotSupported
Validation Target: ParquetFile
Failed Step: 77866d0a-8243-4d3d-8bc6-599d466488dd
Error Message: ScriptExecutionException was caused by StreamAccessException.
  Failed to read Parquet file at: <my_blob_path>/20211217.parquet
    Current parquet file is not supported.
      Exception of type 'Thrift.Protocol.TProtocolException' was thrown.
| session_id=6be4db0b-bdc1-4dd6-b8a6-6e9466f7bc54

By empty parquet file, I mean that the if I read the individual parquet file using pandas (pd.read_parquet), it results in an empty DF (df.empty == True).

Any suggestion to avoid this error will be appreciated.

Update
The issue has been fixed in the following version:

azureml-dataprep : 3.0.1

azureml-core :  1.40.0

Body:
Error Code: ScriptExecution.StreamAccess.Validation

Above error is caused because you are not able to access ADLS.

You can create Azure App Identity and assign read access to ADLS. Now register ADLS as a datastore in workspace using client id and secret of app identity. After these steps your code will be able to access datastore.

Refer - https://learn.microsoft.com/en-us/azure/machine-learning/how-to-network-security-overview#configure-a-datastore-to-use-managed-identity


问:
BASH SHELL SCRIPT to split a big xml file into multiple small files
I have a an XML file in below format

```<code><?xml version="1.0" encoding="utf-8" ?>
<parent>
    <child>
        <code></code>
        <text></text>
    </child>
    <child>
        <code></code>
        <text></text>
    </child>
 </parent>
</code>```

I need a BASH SHELL script to split this main xml file into multiple small XML files which should have contents from the <child> to </child> tag. File names could be parent file name plus a running serial number such as _1 for ex:20110721_1.xml etc..
Please help me with the script.

答:
One solution is to write a XSL file and use xsltproc with the stylesheet and the xml file to generate the single files.

See How to split XML file into many XML files using XSLT for an example.

ContentLicense: CC BY-SA 3.0

Body:
I have a an XML file in below format

<?xml version="1.0" encoding="utf-8" ?>
<parent>
    <child>

        <text></text>
    </child>
    <child>

        <text></text>
    </child>
 </parent>

I need a BASH SHELL script to split this main xml file into multiple small XML files which should have contents from the <child> to </child> tag. File names could be parent file name plus a running serial number such as _1 for ex:20110721_1.xml etc..
Please help me with the script.


问:
Getting 'Reply already sent or deferred' error on Discord interaction (djs)
I am currently building a trivia system and would like to reply every time a user submits an answer to a trivia question. However, I have the following problem with the script below:

```<code>const datahandler = require("../../dataHandler")
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require("discord.js");
const xml = require('xmlhttprequest').XMLHttpRequest
const triviahttp = new xml()

module.exports = {
    data: new SlashCommandBuilder()
        .setName('trivia')
        .setDescription('Answer various trivia questions and earn some quick Jumobos!'),
    async execute(interaction) {
        await interaction.deferReply();
        const difficulties = ['easy', 'medium', 'hard']
        await triviahttp.open('GET', "https://opentdb.com/api.php?amount=1&type=multiple&difficulty=" + difficulties[Math.floor(Math.random()*difficulties.length)])
        await triviahttp.send('');
        triviahttp.addEventListener('load', async function() {
            const data = JSON.parse(triviahttp.responseText)
            const choices = ["", "", "", ""]
            const allanswers = [data.results[0].incorrect_answers[0], data.results[0].incorrect_answers[1], data.results[0].incorrect_answers[2], data.results[0].correct_answer]
            let randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[0] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[1] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[2] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[3] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            let prize = 0;
            if(data.results[0].difficulty == 'easy') {
                prize = "10"
            } else if(data.results[0].difficulty == "medium") {
                prize = "20"
            } else if (data.results[0].difficulty == "hard") {
                prize = "50"
            }
            const triviaembed = new MessageEmbed()
                .setColor('#34faa4')
                .setTitle("<:chat:924420173040066641> Trivia question!")
                .setDescription(`Answer the following question to win some Jumobos. The harder the question, the more Jumobos you may earn! You have 10 seconds to answer the following question. **Reward:** <:jumobo:941073795232460951> ${prize} \n\n **Q:** ${data.results[0].question} \n\n **A.** ${choices[0]} \n **B.** ${choices[1]} \n **C.** ${choices[2]} \n **D.** ${choices[3]} \n\n Please respond with an answer, **A-B-C-D**.`)
                 await interaction.reply({ embeds: [triviaembed], fetchReply: true })
                const filter = m => m.content === "A" || m.content === "B" || m.content === "C" || m.content === "D" && m.author.id == interaction.user.id;
                const collector = interaction.channel.createMessageCollector({filter , max: 1, time: 10000})

                collector.on('collect', message => {
                    message.delete()
                    collector.stop()
                })

               collector.on('end', async collected => {
                   if(collected.size === 0) {
                       await interaction.followUp("You have ran out of time!")

                       return;
                   }
                   let convertlettertochoice = '';
                   if(collected.first().content == "A") convertlettertochoice = "0";
                   if(collected.first().content == "B") convertlettertochoice = "1";
                   if(collected.first().content == "C") convertlettertochoice = "2";
                   if(collected.first().content == "D") convertlettertochoice = "3";
                   console.log(convertlettertochoice)

                   if(choices[convertlettertochoice] == data.results[0].correct_answer) {
                       await interaction.editReply({content: "Hooray! You got this one correct. You have been awarded <:jumobo:941073795232460951> **" + prize + "**.", embeds: []})
                   } else {
                       await interaction.editReply({content: "You got this one incorrect. Yikes! :pensive:", embeds: []})
                   }
                   setTimeout(async () => {
                       await interaction.deleteReply();
                   }, 5000);
               })

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

I get the following error in the console:

```<code>C:\Users\kkost\Desktop\BristoSystems\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90
    if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
                                             ^

Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
    at CommandInteraction.reply (C:\Users\kkost\Desktop\BristoSystems\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90:46)
    at exports.XMLHttpRequest.<anonymous> (C:\Users\kkost\Desktop\BristoSystems\src\commands\economy\trivia.js:46:36)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  [Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
</code>```

I have tried multiple solutions from many other fellow coders but couldn't figure it out so far. Help would be appreciated. Thanks.

答:
On line 46 you are trying to reply, change this to editReply.

Change: await interaction.reply({ embeds: [triviaembed], fetchReply: true })

To: await interaction.editReply({ embeds: [triviaembed] })

Also it might be worth making your code more tidy, then you won't have these issues.

Body:
I am currently building a trivia system and would like to reply every time a user submits an answer to a trivia question. However, I have the following problem with the script below:

const datahandler = require("../../dataHandler")
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require("discord.js");
const xml = require('xmlhttprequest').XMLHttpRequest
const triviahttp = new xml()

module.exports = {
    data: new SlashCommandBuilder()
        .setName('trivia')
        .setDescription('Answer various trivia questions and earn some quick Jumobos!'),
    async execute(interaction) {
        await interaction.deferReply();
        const difficulties = ['easy', 'medium', 'hard']
        await triviahttp.open('GET', "https://opentdb.com/api.php?amount=1&type=multiple&difficulty=" + difficulties[Math.floor(Math.random()*difficulties.length)])
        await triviahttp.send('');
        triviahttp.addEventListener('load', async function() {
            const data = JSON.parse(triviahttp.responseText)
            const choices = ["", "", "", ""]
            const allanswers = [data.results[0].incorrect_answers[0], data.results[0].incorrect_answers[1], data.results[0].incorrect_answers[2], data.results[0].correct_answer]
            let randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[0] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[1] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[2] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            choices[3] = allanswers[randomanswer]
            await allanswers.splice(randomanswer, 1)
            randomanswer = Math.floor(Math.random()*allanswers.length)
            let prize = 0;
            if(data.results[0].difficulty == 'easy') {
                prize = "10"
            } else if(data.results[0].difficulty == "medium") {
                prize = "20"
            } else if (data.results[0].difficulty == "hard") {
                prize = "50"
            }
            const triviaembed = new MessageEmbed()
                .setColor('#34faa4')
                .setTitle("<:chat:924420173040066641> Trivia question!")
                .setDescription(`Answer the following question to win some Jumobos. The harder the question, the more Jumobos you may earn! You have 10 seconds to answer the following question. **Reward:** <:jumobo:941073795232460951> ${prize} \n\n **Q:** ${data.results[0].question} \n\n **A.** ${choices[0]} \n **B.** ${choices[1]} \n **C.** ${choices[2]} \n **D.** ${choices[3]} \n\n Please respond with an answer, **A-B-C-D**.`)
                 await interaction.reply({ embeds: [triviaembed], fetchReply: true })
                const filter = m => m.content === "A" || m.content === "B" || m.content === "C" || m.content === "D" && m.author.id == interaction.user.id;
                const collector = interaction.channel.createMessageCollector({filter , max: 1, time: 10000})

                collector.on('collect', message => {
                    message.delete()
                    collector.stop()
                })

               collector.on('end', async collected => {
                   if(collected.size === 0) {
                       await interaction.followUp("You have ran out of time!")

                       return;
                   }
                   let convertlettertochoice = '';
                   if(collected.first().content == "A") convertlettertochoice = "0";
                   if(collected.first().content == "B") convertlettertochoice = "1";
                   if(collected.first().content == "C") convertlettertochoice = "2";
                   if(collected.first().content == "D") convertlettertochoice = "3";
                   console.log(convertlettertochoice)

                   if(choices[convertlettertochoice] == data.results[0].correct_answer) {
                       await interaction.editReply({content: "Hooray! You got this one correct. You have been awarded <:jumobo:941073795232460951> **" + prize + "**.", embeds: []})
                   } else {
                       await interaction.editReply({content: "You got this one incorrect. Yikes! :pensive:", embeds: []})
                   }
                   setTimeout(async () => {
                       await interaction.deleteReply();
                   }, 5000);
               })

        })
    }
};

I get the following error in the console:

C:\Users\kkost\Desktop\BristoSystems\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90
    if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
                                             ^

Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
    at CommandInteraction.reply (C:\Users\kkost\Desktop\BristoSystems\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90:46)
    at exports.XMLHttpRequest.<anonymous> (C:\Users\kkost\Desktop\BristoSystems\src\commands\economy\trivia.js:46:36)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  [Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}

I have tried multiple solutions from many other fellow coders but couldn't figure it out so far. Help would be appreciated. Thanks.


问:
iframe Fits complete webpage as on Full HD Screen in to a small Window

In first Picture I have 6 iframes being loaded and each having its own HTML page. All pages in those iframes are responsive so they got adjust as per the size.

But I want to make it look like exactly the same those HTML pages would look in 1920x1080 resolution screen (shown in image 2)

Image 2 is the HTML page being loaded in the second row first iframe of Image 1

答:
You can set the high resolution to the frame by default and then zoom and scale it down to the required size.

All you have to do is calculate zoom/scale from starting width to required width.
Which should be required width divided by starting width.

Source of the code with examples.

```<code>#your-frame {
  width: 1920px;
  height: 1080px;
}

#your-frame {
  zoom: 0.50;
  -moz-transform: scale(0.50);
  -moz-transform-origin: 0 0;
  -o-transform: scale(0.50);
  -o-transform-origin: 0 0;
  -webkit-transform: scale(0.50);
  -webkit-transform-origin: 0 0;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  #your-frame {
    zoom: 1;
  }
}

</code>```

Body:
You can set the high resolution to the frame by default and then zoom and scale it down to the required size.

All you have to do is calculate zoom/scale from starting width to required width.
Which should be required width divided by starting width.

Source of the code with examples.

#your-frame {
  width: 1920px;
  height: 1080px;
}

#your-frame {
  zoom: 0.50;
  -moz-transform: scale(0.50);
  -moz-transform-origin: 0 0;
  -o-transform: scale(0.50);
  -o-transform-origin: 0 0;
  -webkit-transform: scale(0.50);
  -webkit-transform-origin: 0 0;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  #your-frame {
    zoom: 1;
  }
}


问:
java: log cannot be resolved
i meet a problem
I use

```<code>IntelliJ IDEA 2017.3.1
Build #IU-173.3942.27, built on December 11, 2017
JRE: 1.8.0_111-b14 amd64
JVM: Java HotSpot(TM) 64-Bit Server VM by Oracle Corporation
Windows 7 6.1
</code>```

Error:(16, 10) java: log cannot be resolved

```<code>import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class LogTest {

    @Test
    public void testSlf4j(){
         log.info("测试 lombok slf4j logback");
    }

}
</code>```

i had config
Settings -> Build, Execution, Deployment -> Compiler -> Annotation Enable annotation processing

Settings -> Other Settings -> Lombok

```<code>    <!-- SLF4J -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>
    <!-- Logback -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.1.3</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>log4j-over-slf4j</artifactId>
        <version>1.7.21</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.20</version>
    </dependency>
</code>```

答:
1.Go to https://projectlombok.org/
2.Download JAR file.
3.Run JAR file. Usually double-clicking JAR file is enough.
4.In the Lombok installation screen, make sure that your Spring Tool Suite instance is listed.
5.Click Install/Update, then Quit Installer.
6.Open Spring Tool Suite, go to About Spring Tool Suite. The large area that contains the version number should have the Lombok version listed at the bottom. You might have to scroll, even though there is no scroll bar.

All the Best.

Title: java: log cannot be resolved

Body:
i meet a problem
I use

IntelliJ IDEA 2017.3.1
Build #IU-173.3942.27, built on December 11, 2017
JRE: 1.8.0_111-b14 amd64
JVM: Java HotSpot(TM) 64-Bit Server VM by Oracle Corporation
Windows 7 6.1

Error:(16, 10) java: log cannot be resolved

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class LogTest {

    @Test
    public void testSlf4j(){
         log.info("测试 lombok slf4j logback");
    }

}

i had config
Settings -> Build, Execution, Deployment -> Compiler -> Annotation Enable annotation processing

Settings -> Other Settings -> Lombok

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.21</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.1.3</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>log4j-over-slf4j</artifactId>
        <version>1.7.21</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.20</version>
    </dependency>


问:
Headless Wordpress Next.js Blog Updates only on Redeployment?
Is this normal for a Headless WP/Next.js setup? When a new post is published from the Wordpress admin, it does not update to the site. In order for it to show I have to go into Vercel and redeploy the site for the blog post to update. This seems a little much to have to redeploy an entire website every time you create a new post. Is this normal or am I missing something?</p>

答: Assuming you're using getStaticProps/Paths to generate your blog posts, you're also going to want to implement Incremental Static Regeneration to revalidate the data at set intervals.</p>


问:
'property' object is not iterable trying to get response after calling the API being used
I have this error when I am trying to get response after the call of the API I want to use.

```<code>ValueError: [TypeError("'property' object is not iterable"),
  TypeError('vars() argument must have __dict__ attribute')]
</code>```

I am trying to use fastapi in order  get from the client the latitudes and longitudes so i could show the public trasnportation of that area. I could do this with an API called GeoApify. However, I have a problem and I can not find my error.

I make a request by using a dictionary in order to put all the parameters for my filter and then I convert the response to JSON. But i have this error.

```<code> from pickletools import string1
    from fastapi import FastAPI
    import requests
    from requests.structures import CaseInsensitiveDict

    app = FastAPI()

    @app.get("/thanos/{lon}/{lat}")
    async def read_item(lat : float,lon : float):
        url = "https://api.geoapify.com/v2/places"
        headers = CaseInsensitiveDict()

        dict = {
            "categories" :   'public_transport',
            "filter"     :   'circle:' + str(lon) + ',' + str(lat) + ",500",
            "limit"      :   '20',
            "apiKey"     :   '086a77f34e3a4ed583da9606318ca0ac'
         }

        params = dict
        headers = CaseInsensitiveDict(params)

        headers["Accept"] = "application/json"

        resp = requests.get(url, headers = headers)

        # resp = requests.get(url = url, params = params)
        data = resp.json
        return resp
</code>```

答:
Use as below:</p>
```<code>from fastapi import FastAPI
import requests
from requests.structures import CaseInsensitiveDict
import urllib

app = FastAPI()

url = "https://api.geoapify.com/v2/places"

@app.get("/{lon}/{lat}")
def read_item(lat : float, lon : float):
    params = {
       "categories" :   'public_transport',
       "filter"     :   'circle:' + str(lon) + ',' + str(lat) + ",500",
       "limit"      :   '20',
       "apiKey"     :   '086a77f34e3a4ed583da9606318ca0ac'
    }

    headers = CaseInsensitiveDict()
    headers["Accept"] = "application/json"

    params = urllib.parse.urlencode(params)
    resp = requests.get(url=url, params=params, headers=headers)

    return resp.json()
</code>```

Body:
I have this error when I am trying to get response after the call of the API I want to use.

ValueError: [TypeError("'property' object is not iterable"),
  TypeError('vars() argument must have __dict__ attribute')]

I am trying to use fastapi in order  get from the client the latitudes and longitudes so i could show the public trasnportation of that area. I could do this with an API called GeoApify. However, I have a problem and I can not find my error.

I make a request by using a dictionary in order to put all the parameters for my filter and then I convert the response to JSON. But i have this error.

 from pickletools import string1
    from fastapi import FastAPI
    import requests
    from requests.structures import CaseInsensitiveDict

    app = FastAPI()

    @app.get("/thanos/{lon}/{lat}")
    async def read_item(lat : float,lon : float):
        url = "https://api.geoapify.com/v2/places"
        headers = CaseInsensitiveDict()

        dict = {
            "categories" :   'public_transport',
            "filter"     :   'circle:' + str(lon) + ',' + str(lat) + ",500",
            "limit"      :   '20',
            "apiKey"     :   '086a77f34e3a4ed583da9606318ca0ac'
         }

        params = dict
        headers = CaseInsensitiveDict(params)

        headers["Accept"] = "application/json"

        resp = requests.get(url, headers = headers)

        # resp = requests.get(url = url, params = params)
        data = resp.json
        return resp

Body:
Use as below:

from fastapi import FastAPI
import requests
from requests.structures import CaseInsensitiveDict
import urllib

app = FastAPI()

url = "https://api.geoapify.com/v2/places"

@app.get("/{lon}/{lat}")
def read_item(lat : float, lon : float):
    params = {
       "categories" :   'public_transport',
       "filter"     :   'circle:' + str(lon) + ',' + str(lat) + ",500",
       "limit"      :   '20',
       "apiKey"     :   '086a77f34e3a4ed583da9606318ca0ac'
    }

    headers = CaseInsensitiveDict()
    headers["Accept"] = "application/json"

    params = urllib.parse.urlencode(params)
    resp = requests.get(url=url, params=params, headers=headers)

    return resp.json()


问:
looping through arrays of arrays
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];
</code>```

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

答:
This recursive function should do the trick with any number of dimensions:</p>

```<code>var printArray = function(arr) {
    if ( typeof(arr) == "object") {
        for (var i = 0; i < arr.length; i++) {
            printArray(arr[i]);
        }
    }
    else document.write(arr);
}

printArray(parentArray);
</code>```

Title: looping through arrays of arrays

Body:
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

Body:
This recursive function should do the trick with any number of dimensions:

var printArray = function(arr) {
    if ( typeof(arr) == "object") {
        for (var i = 0; i < arr.length; i++) {
            printArray(arr[i]);
        }
    }
    else document.write(arr);
}

printArray(parentArray);


问:
Select records that belong to all specified categories
A video can have several categories. I want to select a video that belongs to two categories.

The result returned by this query and that the videos belong to only one of the categories in the condition

SELECT Videos.id, Videos.title
FROM videos Videos
INNER JOIN categories_videos CategoriesVideos
    ON Videos.id = CategoriesVideos.video_id
INNER JOIN categories Categories
    ON Categories.id = CategoriesVideos.category_id AND Categories.id IN (21, 35)
LIMIT 25;
```

I tried to do several joins on the categories table but it doesn't change anything.

Thanks for your help.

答:
You can try the following approach (could be expanded to test n categories):

```<code>SELECT *
FROM videos
WHERE id IN (
    SELECT video_id
    FROM categories_videos
    WHERE category_id IN (21, 35)
    GROUP BY video_id
    HAVING COUNT(*) = 2
)
</code>```

Body:
A video can have several categories. I want to select a video that belongs to two categories.

The result returned by this query and that the videos belong to only one of the categories in the condition

SELECT Videos.id, Videos.title
FROM videos Videos
INNER JOIN categories_videos CategoriesVideos
    ON Videos.id = CategoriesVideos.video_id
INNER JOIN categories Categories
    ON Categories.id = CategoriesVideos.category_id AND Categories.id IN (21, 35)
LIMIT 25;

I tried to do several joins on the categories table but it doesn't change anything.

Thanks for your help.

Body:
You can try the following approach (could be expanded to test n categories):

SELECT *
FROM videos
WHERE id IN (
    SELECT video_id
    FROM categories_videos
    WHERE category_id IN (21, 35)
    GROUP BY video_id
    HAVING COUNT(*) = 2
)


问:
Windows x86_64: "node.exe is not a valid win32 application"
There is a problem with amd64 jdk on amd64 windows and maven-frontend-plugin:

When mvn compile is ran, it grabs amd64 version of node.exe, which is expected; then it tries to run npm.cmd install, to install deps.

Problem is that after that, everything fails:

[ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.0:npm (npm install) on project {projectName}: Failed to run task: 'npm install' failed. java.io.IOException: Cannot run program "D:\Projects\job\projectPath\target\node\node.exe" (in directory "D:\Projects\job\projectPath\src\main\webapp"): CreateProcess error=193, %1 is not a valid Win32 application -> [Help 1]

In case I run x86 jdk, it doesn't fail and builds as normal.

Is the problem on my side, a bug in node.js, in maven-frontend-plugin or in maven itself?

答: What I did, is simply overwrite the node.exe file generated on maven install, by the node.exe file on program files. It works !</p>


问:
Build problem with React viteJS and was amplify
my question is quite simple to explain. I've initialized a React project with ViteJS and then added aws-amplify for the backend. I developed the project and everything works in my local environment running npm run dev. The problem is that I cannot build it.
You can see the error in the text below. Do you have any idea?

'request' is not exported by __vite-browser-external, imported by node_modules/@aws-sdk/credential-provider-imds/dist/es/remoteProvider/httpRequest.js

Error logs

答:
Working config for React polyfilled for AWS SDK and Amplify</p>
```<code>import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: "globalThis", //<-- AWS SDK
      },
    },
  },
  build: {
    rollupOptions: {
      plugins: [
        // Enable rollup polyfills plugin
        // used during production bundling
        rollupNodePolyFill(),
      ],
    },
  },
  resolve: {
    alias: {
      './runtimeConfig': './runtimeConfig.browser', // <-- Fix from above
    },
  }
});
</code>```

Body:
Working config for React polyfilled for AWS SDK and Amplify

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    esbuildOptions: {
      // Node.js global to browser globalThis
      define: {
        global: "globalThis", //<-- AWS SDK
      },
    },
  },
  build: {
    rollupOptions: {
      plugins: [
        // Enable rollup polyfills plugin
        // used during production bundling
        rollupNodePolyFill(),
      ],
    },
  },
  resolve: {
    alias: {
      './runtimeConfig': './runtimeConfig.browser', // <-- Fix from above
    },
  }
});


问:
Kubernetes on docker for windows, persistent volume with hostPath gives Operation not permitted
I am trying to connect a folder in windows to a container folder. This is for a .NET app that needs to read files in a folder. In a normal docker container, with docker-compose, the app works without problems, but since this is only one of several different apps that we will have to monitor, we are trying to get kubernetes involved. That is also where we are failing.
As a beginner with kubernetes, I used kompose.exe to convert the compose files to kuberetes style. However, no matter if I use hostPath or persistentVolumeClaim as a flag, I do not get things to work "out of the box". With hostPath, the path is very incorrect, and with persistentVolumeClaim I get a warning saying volume mount on the host is not supported.
I, therefore, tried to do that part myself but can get it to work with neither persistent volume nor entering mount data in the deployment file directly.
The closest I have come is that I can enter the folder, and I can change to subfolders within, but as soon as I try to run any other command, be it 'ls' or 'cat', I get "Operation not permitted".
Here is my docker compose file, which works as expected by

```<code>version: "3.8"
services:
    test-create-hw-file:
        container_name: "testcreatehwfile"
        image: test-create-hw-file:trygg
        network_mode: "host"
        volumes:
            - /c/temp/testfiles:/app/files
</code>```

Running konvert compose on that file:

```<code>PS C:\temp> .\kompose.exe convert -f .\docker-compose-tchwf.yml --volumes hostPath -v
DEBU Checking validation of provider: kubernetes
DEBU Checking validation of controller:
DEBU Docker Compose version: 3.8
WARN Service "test-create-hw-file" won't be created because 'ports' is not specified
DEBU Compose file dir: C:\temp
DEBU Target Dir: .
INFO Kubernetes file "test-create-hw-file-deployment.yaml" created
</code>```
```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: C:\temp\kompose.exe convert -f .\docker-compose-tchwf.yml --volumes hostPath -v
    kompose.version: 1.26.1 (a9d05d509)
  creationTimestamp: null
  labels:
    io.kompose.service: test-create-hw-file
  name: test-create-hw-file
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: test-create-hw-file
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        kompose.cmd: C:\temp\kompose.exe convert -f .\docker-compose-tchwf.yml --volumes hostPath -v
        kompose.version: 1.26.1 (a9d05d509)
      creationTimestamp: null
      labels:
        io.kompose.service: test-create-hw-file
    spec:
      containers:
        - image: test-create-hw-file:trygg
          name: testcreatehwfile
          resources: {}
          volumeMounts:
            - mountPath: /app/files
              name: test-create-hw-file-hostpath0
      restartPolicy: Always
      volumes:
        - hostPath:
            path: C:\temp\c\temp\testfiles
          name: test-create-hw-file-hostpath0
status: {}
</code>```

Running kubectl apply on that file just gives the infamous error "Error: Error response from daemon: invalid mode: /app/files", which means, as far as I can understand, not that the "/app/files" is wrong, but the format of the supposedly connected folder is incorrect. This is the quite weird C:\temp\c\temp\testfiles row. After googling and reading a lot, I have two ways of changing that, to either /c/temp/testfiles or /host_mnt/c/temp/testfiles. Both end up in the same "Operation not permitted". I am checking this via going into the CLI on the container in the docker desktop.

The image from the test is just an app that does nothing right now other than wait for five minutes to not quit before I can check the folder.
I am logged on to the shell as root, and I have this row for the folder when doing 'ls -lA':

```<code>drwxrwxrwx 1 root root      0 Feb  7 12:04 files
</code>```

Also, the docker-user has full access to the c:\temp\testfiles folder.

Some version data:

```<code>Docker version 20.10.12, build e91ed57

Kubectl version
Client Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.5", GitCommit:"5c99e2ac2ff9a3c549d9ca665e7bc05a3e18f07e", GitTreeState:"clean", BuildDate:"2021-12-16T08:38:33Z", GoVersion:"go1.16.12", Compiler:"gc", Platform:"windows/amd64"}
Server Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.5", GitCommit:"5c99e2ac2ff9a3c549d9ca665e7bc05a3e18f07e", GitTreeState:"clean", BuildDate:"2021-12-16T08:32:32Z", GoVersion:"go1.16.12", Compiler:"gc", Platform:"linux/amd64"}

Kompose version
1.26.1 (a9d05d509)

Host OS: Windows 10, 21H2
</code>```

//Trygg

答:
Glad that my initial comment solved your issue. I would like to expand my thoughts a little in a form of an official answer.

To mount volumes using Kubernetes on Docker Desktop for Windows the path will be:

/run/desktop/mnt/host/c/PATH/TO/FILE
```

Unfortunately there is no official documentation but here is a good comment with explanation that this is related to Docker Daemon:

/mnt/wsl is actually the mount point for the cross-distro mounts tmpfs

Docker Daemon mounts it in its /run/desktop/mnt/host/wsl directory

Body:
I am trying to connect a folder in windows to a container folder. This is for a .NET app that needs to read files in a folder. In a normal docker container, with docker-compose, the app works without problems, but since this is only one of several different apps that we will have to monitor, we are trying to get kubernetes involved. That is also where we are failing.
As a beginner with kubernetes, I used kompose.exe to convert the compose files to kuberetes style. However, no matter if I use hostPath or persistentVolumeClaim as a flag, I do not get things to work "out of the box". With hostPath, the path is very incorrect, and with persistentVolumeClaim I get a warning saying volume mount on the host is not supported.
I, therefore, tried to do that part myself but can get it to work with neither persistent volume nor entering mount data in the deployment file directly.
The closest I have come is that I can enter the folder, and I can change to subfolders within, but as soon as I try to run any other command, be it 'ls' or 'cat', I get "Operation not permitted".
Here is my docker compose file, which works as expected by

version: "3.8"
services:
    test-create-hw-file:
        container_name: "testcreatehwfile"
        image: test-create-hw-file:trygg
        network_mode: "host"
        volumes:
            - /c/temp/testfiles:/app/files

Running konvert compose on that file:

PS C:\temp> .\kompose.exe convert -f .\docker-compose-tchwf.yml --volumes hostPath -v
DEBU Checking validation of provider: kubernetes
DEBU Checking validation of controller:
DEBU Docker Compose version: 3.8
WARN Service "test-create-hw-file" won't be created because 'ports' is not specified
DEBU Compose file dir: C:\temp
DEBU Target Dir: .
INFO Kubernetes file "test-create-hw-file-deployment.yaml" created

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: C:\temp\kompose.exe convert -f .\docker-compose-tchwf.yml --volumes hostPath -v
    kompose.version: 1.26.1 (a9d05d509)
  creationTimestamp: null
  labels:
    io.kompose.service: test-create-hw-file
  name: test-create-hw-file
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: test-create-hw-file
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        kompose.cmd: C:\temp\kompose.exe convert -f .\docker-compose-tchwf.yml --volumes hostPath -v
        kompose.version: 1.26.1 (a9d05d509)
      creationTimestamp: null
      labels:
        io.kompose.service: test-create-hw-file
    spec:
      containers:
        - image: test-create-hw-file:trygg
          name: testcreatehwfile
          resources: {}
          volumeMounts:
            - mountPath: /app/files
              name: test-create-hw-file-hostpath0
      restartPolicy: Always
      volumes:
        - hostPath:
            path: C:\temp\c\temp\testfiles
          name: test-create-hw-file-hostpath0
status: {}

Running kubectl apply on that file just gives the infamous error "Error: Error response from daemon: invalid mode: /app/files", which means, as far as I can understand, not that the "/app/files" is wrong, but the format of the supposedly connected folder is incorrect. This is the quite weird C:\temp\c\temp\testfiles row. After googling and reading a lot, I have two ways of changing that, to either /c/temp/testfiles or /host_mnt/c/temp/testfiles. Both end up in the same "Operation not permitted". I am checking this via going into the CLI on the container in the docker desktop.

The image from the test is just an app that does nothing right now other than wait for five minutes to not quit before I can check the folder.
I am logged on to the shell as root, and I have this row for the folder when doing 'ls -lA':

drwxrwxrwx 1 root root      0 Feb  7 12:04 files

Also, the docker-user has full access to the c:\temp\testfiles folder.

Some version data:

Docker version 20.10.12, build e91ed57

Kubectl version
Client Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.5", GitCommit:"5c99e2ac2ff9a3c549d9ca665e7bc05a3e18f07e", GitTreeState:"clean", BuildDate:"2021-12-16T08:38:33Z", GoVersion:"go1.16.12", Compiler:"gc", Platform:"windows/amd64"}
Server Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.5", GitCommit:"5c99e2ac2ff9a3c549d9ca665e7bc05a3e18f07e", GitTreeState:"clean", BuildDate:"2021-12-16T08:32:32Z", GoVersion:"go1.16.12", Compiler:"gc", Platform:"linux/amd64"}

Kompose version
1.26.1 (a9d05d509)

Host OS: Windows 10, 21H2

//Trygg

Body:
Glad that my initial comment solved your issue. I would like to expand my thoughts a little in a form of an official answer.

To mount volumes using Kubernetes on Docker Desktop for Windows the path will be:

/run/desktop/mnt/host/c/PATH/TO/FILE

Unfortunately there is no official documentation but here is a good comment with explanation that this is related to Docker Daemon:

/mnt/wsl is actually the mount point for the cross-distro mounts tmpfs

Docker Daemon mounts it in its /run/desktop/mnt/host/wsl directory


问:
Java Generics, why is it illegal to use inheritance in generics?
I have this structure:

```<code>///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}
</code>```

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

答:
Take this sample code:

```<code>Movable<Position2D> moveable = new CreepImpl();
MovementStrategy<Movable<Position2D>> strategy=/*some strategy here */;
moveable.setMovementStrategy(strategy);
</code>```

Since CreepImpl only accepts MovementStrategy<Creep>, the last line should fail, although it is perfectly legal, which means that CreepImpl is not a valid substitute for Moveable<Position2D>

In Java, when B extends or implements A, every Object of type B can also be assigned to a variable of type A, and B may not introduce any constraints to limit A.

Body:
I have this structure:

///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

Body:
Take this sample code:

Movable<Position2D> moveable = new CreepImpl();
MovementStrategy<Movable<Position2D>> strategy=/*some strategy here */;
moveable.setMovementStrategy(strategy);

Since CreepImpl only accepts MovementStrategy<Creep>, the last line should fail, although it is perfectly legal, which means that CreepImpl is not a valid substitute for Moveable<Position2D>

In Java, when B extends or implements A, every Object of type B can also be assigned to a variable of type A, and B may not introduce any constraints to limit A.


问:
PHP object loaded as reference in foreach loop
I am looping through an object and i try to duplicate one of the items while changing one of it's variables.

But when i copy the original and then change the title in the new one, the old one changes along with it. Which it shouldn't, since i did not initialised it as a reference.

```<code>$calendar = array(
    (object)[
        'id' => 1,
        'title' => 'original 1',
    ],
    (object)[
        'id' => 2,
        'title' => 'original 2',
    ],
    (object)[
        'id' => 3,
        'title' => 'original 3',
    ],
);

foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $item;
    }
}

echo "```";
print_r($calendar);
die();
```
<p>I would expect the output of this to keep <code>original 2</code> intact. But it changes it along with it.</p>
```(
    [0] => stdClass Object
        (
            [id] => 1
            [title] => original 1
        )

    [1] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [2] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [3] => stdClass Object
        (
            [id] => 3
            [title] => original 3
        )

)
```
<p>Even if i make a new object and use that one to make the changes, it still changes the orignial.</p>
```foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $new_item = $item;
        $new_item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $new_item;
    }
}
```

Now i could probably fix this by just making a new object from scratch and copy the values one by one in it. But where's the fun in that?

So my question is...Why does this happen? Even though i didn't cast $item as &$item

答:
As simple PHP Object assignment does not create a new object. It simply creates a new pointer to the same object.

I think you want to use the clone keyword:

```<code>foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $new_item = clone $item;
        $new_item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $new_item;
    }
}
</code>```

Body:
I am looping through an object and i try to duplicate one of the items while changing one of it's variables.

But when i copy the original and then change the title in the new one, the old one changes along with it. Which it shouldn't, since i did not initialised it as a reference.

$calendar = array(
    (object)[
        'id' => 1,
        'title' => 'original 1',
    ],
    (object)[
        'id' => 2,
        'title' => 'original 2',
    ],
    (object)[
        'id' => 3,
        'title' => 'original 3',
    ],
);

foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $item;
    }
}

echo "
";
print_r($calendar);
die();

I would expect the output of this to keep original 2 intact. But it changes it along with it.

(
    [0] => stdClass Object
        (
            [id] => 1
            [title] => original 1
        )

    [1] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [2] => stdClass Object
        (
            [id] => 2
            [title] => new 2
        )

    [3] => stdClass Object
        (
            [id] => 3
            [title] => original 3
        )

)

Even if i make a new object and use that one to make the changes, it still changes the orignial.

foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $new_item = $item;
        $new_item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $new_item;
    }
}

Now i could probably fix this by just making a new object from scratch and copy the values one by one in it. But where's the fun in that?

So my question is...Why does this happen? Even though i didn't cast $item as &$item

Body:
As simple PHP Object assignment does not create a new object. It simply creates a new pointer to the same object.

I think you want to use the clone keyword:

foreach ($calendar AS $key => $item){
    if($item->id == 2){
        $new_item = clone $item;
        $new_item->title = 'new 2';
        array_splice($calendar, $key, 0, [1]);
        $calendar[$key] = $new_item;
    }
}