问:
How to change calendar permissions for all members of a group?
I'm currently trying to use powershell to change Outlook calendar permissions for a subset of users, so that they can all view calendar details of one another.

So far, I have been able to find the commands to change permissions for a single user, and for all users in the org - but have not yet established how to apply these changes to just a group.

Here is the script I found to modify permissions for all users:

```<code>foreach($user in Get-Mailbox -RecipientTypeDetails UserMailbox) {

$cal = $user.alias+”:\Calendar”

Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights LimitedDetails

}
</code>```

In order to apply this to just a group of users, would my modifications below be correct?

```<code>foreach($user in Get-MsolGroupMember -Identity "Name of Group") {

$cal = $user.alias+”:\Calendar”

Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights LimitedDetails

}
</code>```

答:
You need to first find the group as object, because Get-MsolGroupMember doesn't have a -Identity parameter.

Then use that to get info of its users:

```<code>$groupToFind = 'DisplayName of Group'
$permissions = 'LimitedDetails'
$group = Get-MsolGroup | Where-Object { $_.DisplayName -eq $groupToFind }
if ($group) {
    # get the group members (users only) and run through
    Get-MsolGroupMember -GroupObjectId $group.ObjectId -MemberObjectTypes User -All | ForEach-Object {
        $cal   = '{0}:\Calendar' -f $_.Alias
        $perms = Get-MailboxFolderPermission -Identity $cal -User Default
        if ($perms.AccessRights -contains $permissions) {
                Write-Host "User $($_.Alias) already has the '$permissions' permission"
        }
        else {
            Write-Host "Setting permissions on $cal"
            # for safety, first run with the -WhatIf switch. If you are satisfied with what
            # is output on screen, remove or comment out that switch and run again
            Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights $permissions -WhatIf
        }
    }
}
else {
    Write-Warning "Could not find group '$groupToFind'..."
}
</code>```

Instead of using the Where-Object clause on Get-MsolGroup, you could also do Get-MsolGroup -SearchString $groupToFind, but beware that using -SearchString will return groups that have a display name that START with this string.

If you receive "The command completed successfully, no permissions were changed", this could mean the user first needs to get permissions on the so-called top of the information store (i.e. the mailbox folder itself):

```<code>Get-MsolGroupMember -GroupObjectId $group.ObjectId -MemberObjectTypes User -All | ForEach-Object {
    $top = '{0}:\' -f $_.Alias            # Top of Information Store
    $cal = '{0}:\Calendar' -f $_.Alias

    Add-MailboxFolderPermission -Identity $top -User Default -AccessRights FolderVisible -Confirm:$false
    Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights LimitedDetails -Confirm:$false
}
</code>```

P.S. Because Outlook runs in  cache, it takes time to reflect the changes there.

Body:
I'm currently trying to use powershell to change Outlook calendar permissions for a subset of users, so that they can all view calendar details of one another.

So far, I have been able to find the commands to change permissions for a single user, and for all users in the org - but have not yet established how to apply these changes to just a group.

Here is the script I found to modify permissions for all users:

foreach($user in Get-Mailbox -RecipientTypeDetails UserMailbox) {

$cal = $user.alias+”:\Calendar”

Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights LimitedDetails

}

In order to apply this to just a group of users, would my modifications below be correct?

foreach($user in Get-MsolGroupMember -Identity "Name of Group") {

$cal = $user.alias+”:\Calendar”

Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights LimitedDetails

}

Body:
You need to first find the group as object, because Get-MsolGroupMember doesn't have a -Identity parameter.

Then use that to get info of its users:

$groupToFind = 'DisplayName of Group'
$permissions = 'LimitedDetails'
$group = Get-MsolGroup | Where-Object { $_.DisplayName -eq $groupToFind }
if ($group) {
    # get the group members (users only) and run through
    Get-MsolGroupMember -GroupObjectId $group.ObjectId -MemberObjectTypes User -All | ForEach-Object {
        $cal   = '{0}:\Calendar' -f $_.Alias
        $perms = Get-MailboxFolderPermission -Identity $cal -User Default
        if ($perms.AccessRights -contains $permissions) {
                Write-Host "User $($_.Alias) already has the '$permissions' permission"
        }
        else {
            Write-Host "Setting permissions on $cal"
            # for safety, first run with the -WhatIf switch. If you are satisfied with what
            # is output on screen, remove or comment out that switch and run again
            Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights $permissions -WhatIf
        }
    }
}
else {
    Write-Warning "Could not find group '$groupToFind'..."
}

Instead of using the Where-Object clause on Get-MsolGroup, you could also do Get-MsolGroup -SearchString $groupToFind, but beware that using -SearchString will return groups that have a display name that START with this string.

If you receive "The command completed successfully, no permissions were changed", this could mean the user first needs to get permissions on the so-called top of the information store (i.e. the mailbox folder itself):

Get-MsolGroupMember -GroupObjectId $group.ObjectId -MemberObjectTypes User -All | ForEach-Object {
    $top = '{0}:\' -f $_.Alias            # Top of Information Store
    $cal = '{0}:\Calendar' -f $_.Alias

    Add-MailboxFolderPermission -Identity $top -User Default -AccessRights FolderVisible -Confirm:$false
    Set-MailboxFolderPermission -Identity $cal -User Default -AccessRights LimitedDetails -Confirm:$false
}

P.S. Because Outlook runs in  cache, it takes time to reflect the changes there.


来源: stackexchange

问:
How to handle race-condition (Synchronisation) in Java project using ElasticSearch as persistence
Problem: We have data stored in DB. For example, take a USER object which is stored. CRUD operations can occur on any of the USER.
Is there any efficient way in which I can make these cruds as thread-safe if simultaneous operations come for the same USER.

My Solution

We use a Cache like a concurrent map which will help in holding the lock on specific OID if it is being worked upon.

The issue with this approach is we are having an additional cache, which will be handled in various scenarios like system restart and all.

Is there any other way in which I can achieve this which is much efficient. Anything can be done in persistence layer itself ?

PS: I am not using any Framework.

答:
I think you need to use _seq_no and _primary_term.
You should read the document from the elastic search and retrieve sequence number and primary term:

```<code>request:
GET example-index/_doc/FOjCPXdy5uFjy80o4vxPI4kzlRQo

response:
{
  "_index" : "example-index",
  "_type" : "_doc",
  "_id" : "FOjCPXdy5uFjy80o4vxPI4kzlRQo",
  "_version" : 2,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "data": "text"
  }
}
</code>```

then pass them with your update query:

```<code>request:
POST example-index/_update/FOjCPXdy5uFjy80o4vxPI4kzlRQo?if_seq_no=1&if_primary_term=1
{
  "doc":{
     "data": "updated text"
  }
}
</code>```

so if the other agent updated your document those parameters will change after and you will get error 409:

```<code>response:
{
  "error" : {
    "root_cause" : [
      {
        "type" : "version_conflict_engine_exception",
        "reason" : "[FOjCPXdy5uFjy80o4vxPI4kzlRQo]: version conflict, required seqNo [1], primary term [1]. current document has seqNo [2] and primary term [1]",
        "index_uuid" : "GUZKnab3T5aBlzXEuOPI7Q",
        "shard" : "0",
        "index" : "example-index"
      }
    ],
    "type" : "version_conflict_engine_exception",
    "reason" : "[FOjCPXdy5uFjy80o4vxPI4kzlRQo]: version conflict, required seqNo [1], primary term [1]. current document has seqNo [2] and primary term [1]",
    "index_uuid" : "GUZKnab3T5aBlzXEuOPI7Q",
    "shard" : "0",
    "index" : "example-index"
  },
  "status" : 409
}
</code>```

documentation: elastic.co/optimistic-concurrency-control

ContentLicense: CC BY-SA 4.0

Body:
I think you need to use _seq_no and _primary_term.
You should read the document from the elastic search and retrieve sequence number and primary term:

request:
GET example-index/_doc/FOjCPXdy5uFjy80o4vxPI4kzlRQo

response:
{
  "_index" : "example-index",
  "_type" : "_doc",
  "_id" : "FOjCPXdy5uFjy80o4vxPI4kzlRQo",
  "_version" : 2,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "data": "text"
  }
}

then pass them with your update query:

request:
POST example-index/_update/FOjCPXdy5uFjy80o4vxPI4kzlRQo?if_seq_no=1&if_primary_term=1
{
  "doc":{
     "data": "updated text"
  }
}

so if the other agent updated your document those parameters will change after and you will get error 409:

response:
{
  "error" : {
    "root_cause" : [
      {
        "type" : "version_conflict_engine_exception",
        "reason" : "[FOjCPXdy5uFjy80o4vxPI4kzlRQo]: version conflict, required seqNo [1], primary term [1]. current document has seqNo [2] and primary term [1]",
        "index_uuid" : "GUZKnab3T5aBlzXEuOPI7Q",
        "shard" : "0",
        "index" : "example-index"
      }
    ],
    "type" : "version_conflict_engine_exception",
    "reason" : "[FOjCPXdy5uFjy80o4vxPI4kzlRQo]: version conflict, required seqNo [1], primary term [1]. current document has seqNo [2] and primary term [1]",
    "index_uuid" : "GUZKnab3T5aBlzXEuOPI7Q",
    "shard" : "0",
    "index" : "example-index"
  },
  "status" : 409
}

documentation: elastic.co/optimistic-concurrency-control


问:
Raise an Error if input is an empty list in Python function
I have got the following function which has to check if the input_list is empty.

```<code>def prepare_data(
    input_list: List[np.ndarray], data: Union[np.ndarray, Dict[str, np.ndarray]]
) -> Dict[str, np.ndarray]:
    """[summary]
    Function to dynamically preprare input data to in correct input format for ONNX InferenceSession (dict)
    Parameters
    ----------
    input_list : List[np.ndarray]
        [description]
    data : Union[np.ndarray, Dict[str, np.ndarray]]
        Data for Inferencession which can be an np.array or dictionary with multiple np.arrays

    Returns
    -------
    Dict[str, np.ndarray]
        Dynamic input_feed as dictionary
    """
    if len(input_list) == 0:
        raise IndexError("input_list is not allowed to be an empty list") # Wrong?

    if len(input_list) > 1:
        input_feed = {}
        for feed in input_list:
            input_feed[feed] = data.get(feed)
    else:
        input_feed = {input_list[0]: data}
    return input_feed
</code>```

I tried to solve it with raise IndexError, but I am not sure if that´s the best way or might not even work as expected.

The function has to stop executing if an empty list is passed. What is a good pythonic way to do this?

答:
As @daniyal-ishfaq mentioned you have to correct your conditional first.
Then a good oneliner for such things would be using assert method:

assert len(input_list) > 0, "your error message here"
```

Body:
I have got the following function which has to check if the input_list is empty.

def prepare_data(
    input_list: List[np.ndarray], data: Union[np.ndarray, Dict[str, np.ndarray]]
) -> Dict[str, np.ndarray]:
    """[summary]
    Function to dynamically preprare input data to in correct input format for ONNX InferenceSession (dict)
    Parameters
    ----------
    input_list : List[np.ndarray]
        [description]
    data : Union[np.ndarray, Dict[str, np.ndarray]]
        Data for Inferencession which can be an np.array or dictionary with multiple np.arrays

    Returns
    -------
    Dict[str, np.ndarray]
        Dynamic input_feed as dictionary
    """
    if len(input_list) == 0:
        raise IndexError("input_list is not allowed to be an empty list") # Wrong?

    if len(input_list) > 1:
        input_feed = {}
        for feed in input_list:
            input_feed[feed] = data.get(feed)
    else:
        input_feed = {input_list[0]: data}
    return input_feed

I tried to solve it with raise IndexError, but I am not sure if that´s the best way or might not even work as expected.

The function has to stop executing if an empty list is passed. What is a good pythonic way to do this?


问:
Accessing a dynamically created multi dimensional array with pointers arithmetic
I would like to understand how does it works to scan a dynamically allocated two-dimensional array using pointers arithmetics?

I can't figurate why in my example pointer arithmetic isn't returning the same results as using array indexing.

Here is my implementation:

```<code>    #include <iostream>
    using namespace std;

void init_matrix(int ** m, int size);
void print_matrix(int ** m, int size);
void print_matrix_pointers(int ** m, int size);

int main (){
    srand (time(NULL));
    int size = 3;
    int ** dynamic_matrix = new int * [size];
    for (int i = 0; i < 10; i++) {
        dynamic_matrix[i] = new int [size];
    }
    init_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using square brackets ([i][j]): " << endl;
    print_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using pointers arithmetics: " << endl;
    print_matrix_pointers(dynamic_matrix, size);

    return 0;

}

void init_matrix(int ** m, int size) {
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            m[i][j] = rand()%10;
        }
    }
}

void print_matrix(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << m[i][j] << " ";
        }
        cout << endl;
    }
}

void print_matrix_pointers(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << *(*m + (i * size) + j) << " "; //
        }
        cout << endl;
    }
    cout << endl;
}
</code>```

For instance if size was 3 I would get this output.

Dynamic matrix accessed using array indexing ([i][j]):

3 3 4

9 5 9

4 9 4

Dynamic matrix accessed using pointers arithmetics:

3 3 4

32735 9 5

9 32735 4

答: With *(*m + (i * size) + j) you treat m as a contiguous array of values, which it isn't. It's more like a jagged array. You need to treat it like the array of pointers it really is, like *(*(m + i) + j).

Body:
I would like to understand how does it works to scan a dynamically allocated two-dimensional array using pointers arithmetics?

I can't figurate why in my example pointer arithmetic isn't returning the same results as using array indexing.

Here is my implementation:

    #include <iostream>
    using namespace std;

void init_matrix(int ** m, int size);
void print_matrix(int ** m, int size);
void print_matrix_pointers(int ** m, int size);

int main (){
    srand (time(NULL));
    int size = 3;
    int ** dynamic_matrix = new int * [size];
    for (int i = 0; i < 10; i++) {
        dynamic_matrix[i] = new int [size];
    }
    init_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using square brackets ([i][j]): " << endl;
    print_matrix(dynamic_matrix, size);

    cout << "Dynamic matrix accessed using pointers arithmetics: " << endl;
    print_matrix_pointers(dynamic_matrix, size);

    return 0;

}

void init_matrix(int ** m, int size) {
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            m[i][j] = rand()%10;
        }
    }
}

void print_matrix(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << m[i][j] << " ";
        }
        cout << endl;
    }
}

void print_matrix_pointers(int ** m, int size){
    for (int i = 0; i < size; i++){
        for (int j = 0; j < size; j++){
            cout << *(*m + (i * size) + j) << " "; //
        }
        cout << endl;
    }
    cout << endl;
}

For instance if size was 3 I would get this output.

Dynamic matrix accessed using array indexing ([i][j]):

3 3 4

9 5 9

4 9 4

Dynamic matrix accessed using pointers arithmetics:

3 3 4

32735 9 5

9 32735 4


问:
How do I download my model using wget so that I can upload it to streamlit?
I saved my emotion detection model as a .h5. It's too big to be uploaded to Github so i uploaded it to dropbox and used wget to download the model, so that I can deploy it to streamlit. This is my code:

if not os.path.exists("models/emotion_detection_model_for_streamlit.h5"):
    with st.spinner("Loading model..."):
        os.system("wget --no-check-certificate -O
models/emotion_detection_model_for_streamlit.h5 \"link-to-model"")

model = tf.keras.models.load_model("models/emotion_detection_model_for_streamlit.h5")
```

When deploying the app via streamlit, I am getting the following error:
link to error message from streamlit

[manager] Python dependencies were installed from /app/emotion-in-motion-2/requirements.txt using pip.
[manager] Processed dependencies!
2022-02-11 10:34:22.712519: W tensorflow/stream executor/platform/default/do loader.cc:64] Could not load dynamic library 'libcudart.so.11.0';
dlerror: libel
2022-02-11 10:34:22.712601: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
sh: 1: wget: not found
2022-02-11 10:34:25.828 Uncaught app
exception
Traceback (most recent call last):
File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py"
line 350, in
run_script
exec (code, module.
dict_)
File "/app/emotion-in-motion-2/app.py", line 30, in
model = tf.keras.models.load_model("models/emotion_detection_model_for_streamlit.h5")
File "/home/appuser/venv/lib/python3.7/site-packages/keras/utils/traceback_utils.py",
line 67, in error_handler
raise e.with_traceback(filtered _tb) from None
File "/home/appuser/venv/lib/python3.7/site-packages/keras/saving/save.py"
line 204, in load model
raise I0Error (f'No file or directory found at {filepath_str}')
OSError: No file or directory found at models/emotion _detection_model_for_streamlit.h5
[client] Connecting...
sh: 1: wget: not found
2022-02-11 10:34:33.564 Uncaught app exception
Traceback (most recent call last) :
File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py"
line 350, in
run_script
exec (code, module.
dict.
File
"/app/emotion-in-motion-2/app.py"
, line 30.
in
«module>
model
=tf.keras.models.load_model("models/emotion_detection_model_for_streamlit.h5")
File "/home/appuser/venv/lib/python3.7/site-packages/keras/utils/traceback_utils.py",line67,inerror_handler
raise e.with_traceback(filtered_tb) from None
File "/home/appuser/venv/lib/python3.7/site-packages/keras/saving/save.py",line 204, in load model
raise I0Error (f' No file or directory found at {filepath_str}'
OSError: No file or directory found at models/emotion_detection model_for_streamlit.h5

Please help

答: It looks like the wget command is not found. You could try to use curl instead.

Body:
I saved my emotion detection model as a .h5. It's too big to be uploaded to Github so i uploaded it to dropbox and used wget to download the model, so that I can deploy it to streamlit. This is my code:

if not os.path.exists("models/emotion_detection_model_for_streamlit.h5"):
    with st.spinner("Loading model..."):
        os.system("wget --no-check-certificate -O
models/emotion_detection_model_for_streamlit.h5 \"link-to-model"")

model = tf.keras.models.load_model("models/emotion_detection_model_for_streamlit.h5")

When deploying the app via streamlit, I am getting the following error:
link to error message from streamlit

[manager] Python dependencies were installed from /app/emotion-in-motion-2/requirements.txt using pip.
[manager] Processed dependencies!
2022-02-11 10:34:22.712519: W tensorflow/stream executor/platform/default/do loader.cc:64] Could not load dynamic library 'libcudart.so.11.0';
dlerror: libel
2022-02-11 10:34:22.712601: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
sh: 1: wget: not found
2022-02-11 10:34:25.828 Uncaught app
exception
Traceback (most recent call last):
File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py"
line 350, in
run_script
exec (code, module.
dict_)
File "/app/emotion-in-motion-2/app.py", line 30, in
model = tf.keras.models.load_model("models/emotion_detection_model_for_streamlit.h5")
File "/home/appuser/venv/lib/python3.7/site-packages/keras/utils/traceback_utils.py",
line 67, in error_handler
raise e.with_traceback(filtered _tb) from None
File "/home/appuser/venv/lib/python3.7/site-packages/keras/saving/save.py"
line 204, in load model
raise I0Error (f'No file or directory found at {filepath_str}')
OSError: No file or directory found at models/emotion _detection_model_for_streamlit.h5
[client] Connecting...
sh: 1: wget: not found
2022-02-11 10:34:33.564 Uncaught app exception
Traceback (most recent call last) :
File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py"
line 350, in
run_script
exec (code, module.
dict.
File
"/app/emotion-in-motion-2/app.py"
, line 30.
in
«module>
model
=tf.keras.models.load_model("models/emotion_detection_model_for_streamlit.h5")
File "/home/appuser/venv/lib/python3.7/site-packages/keras/utils/traceback_utils.py",line67,inerror_handler
raise e.with_traceback(filtered_tb) from None
File "/home/appuser/venv/lib/python3.7/site-packages/keras/saving/save.py",line 204, in load model
raise I0Error (f' No file or directory found at {filepath_str}'
OSError: No file or directory found at models/emotion_detection model_for_streamlit.h5

Please help


问:
Batch one line to call an executable using arguments from file
For convenience, I have renamed all the files to simple names for my example.

I'm trying to run an executable (test.exe), with a C++ entrypoint int main(int argc, char* argv[]) from a batch file (test.bat), and pass arguments from a text file (test.txt). The end goal is to run unit tests on an SDK using the testing software (test.exe).

My issue is that I do not want to have to use a variable when I call the executable since it makes the code harder to read :

rem This works
set /p test_input=<test.txt& call test.exe %test_input%
```
<p>After some research, I figured I should use <strong>input redirection</strong> like so :</p>
<pre class="lang-bsh prettyprint-override"><code>rem This does not work
call test.exe < test.txt
</code>```

This does not work, and I don't understand why.

This is what I initially tried, and it has been suggested before on SO (here).
I have access to the test.exe code, so I can print argc and argv :

int main(int argc, char* argv[])
{
    if(new_argc >= 2)
    {
        if(strcmp("-help", argv[1]) ==0)
        {
            show_help();
            return 0;
        }
        for(int i=1; i < argc; i++)
        {
            if(strcmp("-framerate", argv[i]) ==0)
            {
                i++;
                if(i < argc)
                {
                    FrameRate = (float)atof(argv[i]);
                }
                else
                {
                    std::cerr << "Parameters error" << std::endl;
                    return 0;
                }
            } else if ...
            {
                ...
            }
        }
    }
}
```
<p>If I enter the arguments and parameters manually, it works as expected.</p>
<p>test.txt</p>
```-arg1 param1 -arg2 param2 ...
```
<p>test.bat</p>
<pre class="lang-bsh prettyprint-override"><code>call test.exe < test.txt
</code>```

Output : test.exe runs as if there are no arguments or parameters.

Edit :
Added a few details about the entrypoint and renamed the batch variable.

答:
Thanks to the comments under my question, I was pushed in the right direction.

The problem was my understanding of <. It literally means "Read file to STDIN" (as mentionned here). Many other documentation sites give vague definitions like (as mentionned here)

command < filename : Type a text file and pass the text to command

I need to parse the input correctly, since stdin isn't available in argc or argv, but through std::cin.

My batch code and text file remain unchanged, and I want to maintain the same form of parsing to avoid rewriting multiple projects, so I split the input string using the Solution 1.3 from here (slightly modified) and created a new_argv.

std::vector<char*> split(const std::string& s, char delimiter)
{
    std::vector<char*> tokens;
    std::string token;
    std::istringstream tokenStream(s);
    while (std::getline(tokenStream, token, delimiter))
    {
        tokens.push_back(_strdup(token.c_str()));
    }
    return tokens;
}

int main(int argc, char* argv[])
{
    std::string extra_input; // Variable to store the contents of test.txt
    std::getline(std::cin, extra_input); // Recuperate the contents of test.txt
    std::vector<char*> new_argv = split(extra_input, ' '); // Split the args
    for(int i = argc - 1; i >= 0; i--)
        new_argv.insert(new_argv.begin(), argv[i]); // Add the original args to the beginning
    const size_t new_argc = new_argv.size(); // Create the new argc based on the final argument list (vector)

    if(new_argc >= 2)
    {
        if(strcmp("-help", new_argv[1]) ==0)
        {
            show_help();
            return 0;
        }
        for(int i=1; i < new_argc; i++)
        {
            if(strcmp("-framerate", new_argv[i]) ==0)
            {
                i++;
                if(i < new_argc)
                {
                    FrameRate = (float)atof(new_argv[i]);
                }
                else
                {
                    std::cerr << "Parameters error" << std::endl;
                    return 0;
                }
            } else if ...
            {
                ...
            }
        }
    }
    // Important, don't forget to free the memory used by the _strdup
    for(int i=1; i < new_argc; i++)
    {
        if(i >= argc)
            free(new_argv[i]);
    }
}
```
<p>test.bat</p>
```call test.exe < test.txt
```
<p>test.txt</p>
```-arg1 param1 -arg2 param2 ...
```

Of course, I need to add some checks to make it properly handle whitespace, but that's the gist of it. Thank you for your help and external point of view.

Edit : Fixed a mistake in the code.

Body:
For convenience, I have renamed all the files to simple names for my example.

I'm trying to run an executable (test.exe), with a C++ entrypoint int main(int argc, char* argv[]) from a batch file (test.bat), and pass arguments from a text file (test.txt). The end goal is to run unit tests on an SDK using the testing software (test.exe).

My issue is that I do not want to have to use a variable when I call the executable since it makes the code harder to read :

rem This works
set /p test_input=<test.txt& call test.exe %test_input%

After some research, I figured I should use input redirection like so :

rem This does not work
call test.exe < test.txt

This does not work, and I don't understand why.

This is what I initially tried, and it has been suggested before on SO (here).
I have access to the test.exe code, so I can print argc and argv :

int main(int argc, char* argv[])
{
    if(new_argc >= 2)
    {
        if(strcmp("-help", argv[1]) ==0)
        {
            show_help();
            return 0;
        }
        for(int i=1; i < argc; i++)
        {
            if(strcmp("-framerate", argv[i]) ==0)
            {
                i++;
                if(i < argc)
                {
                    FrameRate = (float)atof(argv[i]);
                }
                else
                {
                    std::cerr << "Parameters error" << std::endl;
                    return 0;
                }
            } else if ...
            {
                ...
            }
        }
    }
}

If I enter the arguments and parameters manually, it works as expected.

test.txt

-arg1 param1 -arg2 param2 ...

test.bat

call test.exe < test.txt

Output : test.exe runs as if there are no arguments or parameters.

Edit :
Added a few details about the entrypoint and renamed the batch variable.

Body:
Thanks to the comments under my question, I was pushed in the right direction.

The problem was my understanding of <. It literally means "Read file to STDIN" (as mentionned here). Many other documentation sites give vague definitions like (as mentionned here)

command < filename : Type a text file and pass the text to command

I need to parse the input correctly, since stdin isn't available in argc or argv, but through std::cin.

My batch code and text file remain unchanged, and I want to maintain the same form of parsing to avoid rewriting multiple projects, so I split the input string using the Solution 1.3 from here (slightly modified) and created a new_argv.

std::vector<char*> split(const std::string& s, char delimiter)
{
    std::vector<char*> tokens;
    std::string token;
    std::istringstream tokenStream(s);
    while (std::getline(tokenStream, token, delimiter))
    {
        tokens.push_back(_strdup(token.c_str()));
    }
    return tokens;
}

int main(int argc, char* argv[])
{
    std::string extra_input; // Variable to store the contents of test.txt
    std::getline(std::cin, extra_input); // Recuperate the contents of test.txt
    std::vector<char*> new_argv = split(extra_input, ' '); // Split the args
    for(int i = argc - 1; i >= 0; i--)
        new_argv.insert(new_argv.begin(), argv[i]); // Add the original args to the beginning
    const size_t new_argc = new_argv.size(); // Create the new argc based on the final argument list (vector)

    if(new_argc >= 2)
    {
        if(strcmp("-help", new_argv[1]) ==0)
        {
            show_help();
            return 0;
        }
        for(int i=1; i < new_argc; i++)
        {
            if(strcmp("-framerate", new_argv[i]) ==0)
            {
                i++;
                if(i < new_argc)
                {
                    FrameRate = (float)atof(new_argv[i]);
                }
                else
                {
                    std::cerr << "Parameters error" << std::endl;
                    return 0;
                }
            } else if ...
            {
                ...
            }
        }
    }
    // Important, don't forget to free the memory used by the _strdup
    for(int i=1; i < new_argc; i++)
    {
        if(i >= argc)
            free(new_argv[i]);
    }
}

test.bat

call test.exe < test.txt

test.txt

-arg1 param1 -arg2 param2 ...

Of course, I need to add some checks to make it properly handle whitespace, but that's the gist of it. Thank you for your help and external point of view.

Edit : Fixed a mistake in the code.


问:
Send Meeting URL using Google Meet API
I want to create Java Spring application using google meet api where I'll generate a meeting link using which two people could join. Basically, it's like creating an event for two attendees (user could be of any domain) and send them meeting link using which they can join at some scheduled time using google hangout.

I tried this example here: https://developers.google.com/calendar/v3/reference/events#resource

But I think this is not the right one since want to generate meeting invite link where two random users can join using a link and in their response there's a hangout link which can only be used by domain users.

Also, in this link, it is mentioned that we can generate meeting URLs with no API calls but then guests who aren't part of my domain won't be able to join and I wanted to have an independent meeting link.

Can someone please point me in the right direction?

答:
You could maybe create a Google Calendar Event and associate it with Google Meet (hangoutsMeet).
https://developers.google.com/calendar/api/guides/create-events</p>

Title: Send Meeting URL using Google Meet API


问:
How to authenticate user using custom model in Django?
I am working on a Django project. The project has three pages Home, login, registration. Home page's nav bar has three buttons Home, login and registration. I have created a custom model I don't want to admin model. I already did the login part but now I want is after login the home nav login and register button disappear and a new button/text appear Hello user or whatever the name whoever is logged in.
Is there any way to do it I know we can do it with the admin User model but I don't know how to do it with a custom model?

models.py

class  user_detail(models.Model):
    email = models.EmailField(("email"), max_length=254)
    first_name = models.CharField( ("first name"),max_length=50)
    last_name = models.CharField(("last name"), max_length=50)
    address = models.CharField(("address"), max_length=50)
    phone_number = models.IntegerField(("phone number"))
    password = models.CharField(("password"), max_length=50)

```
<p><strong>views.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from .models import user_detail

class loginView(TemplateView):
    template_name = 'accounts/login.html'

    def post(self, request):
        if request.method == 'POST':
            print(request)
            html_email = request.POST['email']
            html_password = request.POST['password']

        user = user_detail.objects.values_list('email',flat = True)
        if html_email in list(user):
            user_password = user_detail.objects.filter(email = html_email).values_list('password',flat = True)[0]
            print(user_password)

            if user_password == html_password :
                return redirect('/home/')
        else:
            print(" incorrect credentials ")

        return render(request, 'accounts/login.html')
</code>```

Edit: what I need is whenever some is logged in login/register button disappear and welcome ,+ first_name .

答:
The best way to having a custom user model is that to use AbstractUser.
you should do it like this:</p>
```<code>Class User(AbstractUser):
    # add your custom field here
    birth_date=models.IntegerField()
</code>```

Body:
I am working on a Django project. The project has three pages Home, login, registration. Home page's nav bar has three buttons Home, login and registration. I have created a custom model I don't want to admin model. I already did the login part but now I want is after login the home nav login and register button disappear and a new button/text appear Hello user or whatever the name whoever is logged in.
Is there any way to do it I know we can do it with the admin User model but I don't know how to do it with a custom model?

models.py

class  user_detail(models.Model):
    email = models.EmailField(("email"), max_length=254)
    first_name = models.CharField( ("first name"),max_length=50)
    last_name = models.CharField(("last name"), max_length=50)
    address = models.CharField(("address"), max_length=50)
    phone_number = models.IntegerField(("phone number"))
    password = models.CharField(("password"), max_length=50)

views.py

from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from .models import user_detail

class loginView(TemplateView):
    template_name = 'accounts/login.html'

    def post(self, request):
        if request.method == 'POST':
            print(request)
            html_email = request.POST['email']
            html_password = request.POST['password']

        user = user_detail.objects.values_list('email',flat = True)
        if html_email in list(user):
            user_password = user_detail.objects.filter(email = html_email).values_list('password',flat = True)[0]
            print(user_password)

            if user_password == html_password :
                return redirect('/home/')
        else:
            print(" incorrect credentials ")

        return render(request, 'accounts/login.html')

Edit: what I need is whenever some is logged in login/register button disappear and welcome ,+ first_name .

Body:
The best way to having a custom user model is that to use AbstractUser.
you should do it like this:

Class User(AbstractUser):
    # add your custom field here
    birth_date=models.IntegerField()


问:
TS: How to make returning type be a type of interface property with enum keys
My goal is to make a set-method with prop_key and prop_value arguments that decide a type of prop_value on the value of a prop_key.

I want it to use enum as prop names and an interface as types of prop values.

What I want to do:

```<code>enum Property {
  A = 0,
  B,
  C
}

interface PropertyStorage {
  [Properties.A]: number;
  [Properties.B]: string;
  [Properties.C]: boolean;
}

setProperty(name: Property, value: TypeOfThisPropertyInStorage?): void

// Example
// setProterty(Propert.A, value => number)
// setProterty(Property.B, value => string)
// setProterty(Property.C, value => boolean)
</code>```

Recently I've tried:

```<code>setProperty(name: Property, value: Pick<PropertyStorage , typeof name>): void
</code>```

But when I try to use it I get:

```<code>setProperty(Property.A, 15)
// Argument of type 'number' is not assignable to parameter of type 'Pick<PropertyStorage , Property>'.
</code>```

答:
As @captain-yossarian mentioned- solution is</p>
```<code>enum Property {
    A = 0,
    B,
    C
}

interface PropertyStorage {
    [Property.A]: number;
    [Property.B]: string;
    [Property.C]: boolean;
}

const setProperty = <Name extends keyof PropertyStorage>(name: Name, value: PropertyStorage[Name]) => {

}

setProperty(Property.A, 42)
</code>```

Body:
My goal is to make a set-method with prop_key and prop_value arguments that decide a type of prop_value on the value of a prop_key.

I want it to use enum as prop names and an interface as types of prop values.

What I want to do:

enum Property {
  A = 0,
  B,
  C
}

interface PropertyStorage {
  [Properties.A]: number;
  [Properties.B]: string;
  [Properties.C]: boolean;
}

setProperty(name: Property, value: TypeOfThisPropertyInStorage?): void

// Example
// setProterty(Propert.A, value => number)
// setProterty(Property.B, value => string)
// setProterty(Property.C, value => boolean)

Recently I've tried:

setProperty(name: Property, value: Pick<PropertyStorage , typeof name>): void

But when I try to use it I get:

setProperty(Property.A, 15)
// Argument of type 'number' is not assignable to parameter of type 'Pick<PropertyStorage , Property>'.

Body:
As @captain-yossarian mentioned- solution is

enum Property {
    A = 0,
    B,
    C
}

interface PropertyStorage {
    [Property.A]: number;
    [Property.B]: string;
    [Property.C]: boolean;
}

const setProperty = <Name extends keyof PropertyStorage>(name: Name, value: PropertyStorage[Name]) => {

}

setProperty(Property.A, 42)


问:
How can I use Flask-migrate across multiple development environments
I have flask-migrate (version 1.8.0) working well with a sqlite database in a development environment.  Now I would like to migrate our data to MySQL and maintain all of our migration history (so it stays in sync with our Flask-SQLAlchemy models in our git repository).

I created an empty MySQL database, and after changing my SQLALCHEMY_DATABASE_URI, I tried running:

```<code>python manage.py db upgrade
</code>```

That resulted in an error about not being able to drop the table migrate_version.  (Which makes sense, since this is a new database, although sqlite actually contains the table 'alembic_version' not 'migrate_version'.)

So, I tried to initialize this new database:

```<code>python manage.py db init
</code>```

Now I get an error: "Directory migrations already exists".

I can rename that folder and re-run the command with no problem, but then I lose all of my previous migrations.  I think we would have the same issues when we also transition to our test and production environments.

I've seen in the docs Flask-Migrate has multiple database support, but I think that looks to be more for maintaining multiple databases in a single development environment.  Is there a way to have Flask-Migrate track changes across multiple development environments?

答:
I also had the same need on my side. I wanted to reproduce the command that exists in the laravel framework to make a migration in different environments:

```<code>php artisan migrate --env prod
</code>```

With this kind of command, you can launch a migration in different environments. I have not found a directly equivalent command in flask.

THE "flask db upgrade --env prod" command does not exist. In particular, the --env argument .

As a workaround, I created a command that allows me to change the environment:

```<code>flask env --name prod
</code>```

That command is a custom flask command that will copy the content of the .env.prod file to .env.

This way, the application is in the prod environment. And we can then launch the migration command on the prod environment.

How to use the custom env command to migrate to different environments?

To start the migration in the staging environment, just run these two commands:

```<code>flask env --name staging
flask db updgrade
</code>```

Then if you want to start the migration in the production environment, just run these two commands:

```<code>flask env --name prod
flask db updgrade
</code>```

How to create the custom command flask env?

First, you need to know how to create custom command in flask. Just follow the official falsk documentation

Here is the content of my custom command which allows to change the environment:

```<code>from flask.cli import with_appcontext
import shutil

@click.command('env')
@click.option("--name", is_flag=False, flag_value="Flag", default="")
@with_appcontext
def env(name):
    if name == '':
        print(os.getenv('FLASK_ENV'))
        return

    if name not in ['dev', 'prod', 'local', 'staging']:
        print('That env does not exist')
        return

    shutil.copyfile('.env.' + name, '.env')

    return

</code>```

In my setup, I have 4 environments: local, dev, staging, prod.

And I have 4 corresponding .env files: .env.local, .env.staging, .env.prod, .env.dev

The custom flask env command also copies the contents of the environment files into the .env file that the flask application loads at start-up.

ContentLicense: CC BY-SA 3.0

Body:
I have flask-migrate (version 1.8.0) working well with a sqlite database in a development environment.  Now I would like to migrate our data to MySQL and maintain all of our migration history (so it stays in sync with our Flask-SQLAlchemy models in our git repository).

I created an empty MySQL database, and after changing my SQLALCHEMY_DATABASE_URI, I tried running:

python manage.py db upgrade

That resulted in an error about not being able to drop the table migrate_version.  (Which makes sense, since this is a new database, although sqlite actually contains the table 'alembic_version' not 'migrate_version'.)

So, I tried to initialize this new database:

python manage.py db init

Now I get an error: "Directory migrations already exists".

I can rename that folder and re-run the command with no problem, but then I lose all of my previous migrations.  I think we would have the same issues when we also transition to our test and production environments.

I've seen in the docs Flask-Migrate has multiple database support, but I think that looks to be more for maintaining multiple databases in a single development environment.  Is there a way to have Flask-Migrate track changes across multiple development environments?

Body:
I also had the same need on my side. I wanted to reproduce the command that exists in the laravel framework to make a migration in different environments:

php artisan migrate --env prod

With this kind of command, you can launch a migration in different environments. I have not found a directly equivalent command in flask.

THE "flask db upgrade --env prod" command does not exist. In particular, the --env argument .

As a workaround, I created a command that allows me to change the environment:

flask env --name prod

That command is a custom flask command that will copy the content of the .env.prod file to .env.

This way, the application is in the prod environment. And we can then launch the migration command on the prod environment.

How to use the custom env command to migrate to different environments?

To start the migration in the staging environment, just run these two commands:

flask env --name staging
flask db updgrade

Then if you want to start the migration in the production environment, just run these two commands:

flask env --name prod
flask db updgrade

How to create the custom command flask env?

First, you need to know how to create custom command in flask. Just follow the official falsk documentation

Here is the content of my custom command which allows to change the environment:

from flask.cli import with_appcontext
import shutil

@click.command('env')
@click.option("--name", is_flag=False, flag_value="Flag", default="")
@with_appcontext
def env(name):
    if name == '':
        print(os.getenv('FLASK_ENV'))
        return

    if name not in ['dev', 'prod', 'local', 'staging']:
        print('That env does not exist')
        return

    shutil.copyfile('.env.' + name, '.env')

    return

In my setup, I have 4 environments: local, dev, staging, prod.

And I have 4 corresponding .env files: .env.local, .env.staging, .env.prod, .env.dev

The custom flask env command also copies the contents of the environment files into the .env file that the flask application loads at start-up.


问:
Unmarshalling a TreeSet in JAXB
I have a class that I wish to populate with content from an XML file using JAXB. My XML file looks similar to this:

```<code><root>
  <mylist>
    <item id="1">First Item</item>
    <item id="2">Second Item</item>
  </mylist>
</root>
</code>```

My JAXB annotated classes look like:

```<code>@XmlRootElement
class MyParentClass {

  // I always populate this with a TreeSet
  private Set<MyFieldItem> items;

  public void setItems(Set<MyFieldItem> items) {
    this.items = items;
  }

  @XmlElementWrapper("mylist") @XmlElement("item")
  public Set<MyFieldItem> getItems() {
    return items;
  }
}

class MyFieldItem implements Comparable<MyFieldItem> {
  private Integer id;
  private String value;

  public void setId(Integer id) {
    this.id = id;
  }

  @XmlAttribute
  public Integer getId() {
    return id;
  }

  public void setValue(String value) {
    this.value = value;
  }

  @XmlValue
  public String getValue() {
    return value;
  }

  public int compareTo(MyfieldItem o) {
    return this.id.compareTo(o.getId());
  }
}
</code>```

I find that this arrangement serialises my objects to XML correctly, but when I try to convert it back the TreeSet I use becomes a HashSet.

In theory my collection could be fixed to a TreeSet (which does fix the problem), but I'd rather configure JAXB correctly and defer that logic elsewhere. How do I tell JAXB to build a TreeSet instead?

答:
The easiest way to solve this problem is pre-initialize your Set property to the appropriate implementation type, and your JAXB implmentation (Metro, EclipseLink MOXy, Apache JaxMe, etc) will use that instead of creating a new Set:

```<code>package forum7104810;

import java.util.Set;
import java.util.TreeSet;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="root")
class MyParentClass {

  // Initialize this property with an instance of the desired type.
  private Set<MyFieldItem> items = new TreeSet<MyFieldItem>();

  public void setItems(Set<MyFieldItem> items) {
    this.items = items;
  }

  @XmlElementWrapper(name="mylist")
  @XmlElement(name="item")
  public Set<MyFieldItem> getItems() {
    return items;
  }

}
</code>```

For More Information

http://blog.bdoughan.com/2011/01/jaxb-and-choosing-list-implementation.html

Title: Unmarshalling a TreeSet in JAXB

Body:
I have a class that I wish to populate with content from an XML file using JAXB. My XML file looks similar to this:

<root>
  <mylist>
    <item id="1">First Item</item>
    <item id="2">Second Item</item>
  </mylist>
</root>

My JAXB annotated classes look like:

@XmlRootElement
class MyParentClass {

  // I always populate this with a TreeSet
  private Set<MyFieldItem> items;

  public void setItems(Set<MyFieldItem> items) {
    this.items = items;
  }

  @XmlElementWrapper("mylist") @XmlElement("item")
  public Set<MyFieldItem> getItems() {
    return items;
  }
}

class MyFieldItem implements Comparable<MyFieldItem> {
  private Integer id;
  private String value;

  public void setId(Integer id) {
    this.id = id;
  }

  @XmlAttribute
  public Integer getId() {
    return id;
  }

  public void setValue(String value) {
    this.value = value;
  }

  @XmlValue
  public String getValue() {
    return value;
  }

  public int compareTo(MyfieldItem o) {
    return this.id.compareTo(o.getId());
  }
}

I find that this arrangement serialises my objects to XML correctly, but when I try to convert it back the TreeSet I use becomes a HashSet.

In theory my collection could be fixed to a TreeSet (which does fix the problem), but I'd rather configure JAXB correctly and defer that logic elsewhere. How do I tell JAXB to build a TreeSet instead?

Body:
The easiest way to solve this problem is pre-initialize your Set property to the appropriate implementation type, and your JAXB implmentation (Metro, EclipseLink MOXy, Apache JaxMe, etc) will use that instead of creating a new Set:

package forum7104810;

import java.util.Set;
import java.util.TreeSet;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="root")
class MyParentClass {

  // Initialize this property with an instance of the desired type.
  private Set<MyFieldItem> items = new TreeSet<MyFieldItem>();

  public void setItems(Set<MyFieldItem> items) {
    this.items = items;
  }

  @XmlElementWrapper(name="mylist")
  @XmlElement(name="item")
  public Set<MyFieldItem> getItems() {
    return items;
  }

}

For More Information

http://blog.bdoughan.com/2011/01/jaxb-and-choosing-list-implementation.html


问:
Could not set unknown property 'mainClass' for extension 'application
I'm using Gradle version 6.1 in my project.

The build.gradle for the project is given below :

```<code>plugins {
    id 'application'
}

application {
    mainClass = 'com.mytestproject.Main'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

group 'com.mytestproject'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}
</code>```

But when I run this command ./gradlew assemble, it is giving me error given below :

```<code>./gradlew assemble

FAILURE: Build failed with an exception.

* Where:
Build file '/com/myproject/build.gradle' line: 6

* What went wrong:
A problem occurred evaluating root project 'JavaTestProject'.
> Could not set unknown property 'mainClass' for extension 'application' of type org.gradle.api.plugins.internal.DefaultJavaApplication.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 484ms
</code>```

答:
Actually just modifying the application block to

```<code>application {
    mainClassName = 'com.mytestproject.Main'
}
</code>```

does the same thing.

The problem seems to be that there used to be a mainClass attribute on the org.gradle.api.plugins.internal.DefaultJavaApplication class, but it later got renamed to mainClassName, rendering previous tutorials invalid.

Body:
I'm using Gradle version 6.1 in my project.

The build.gradle for the project is given below :

plugins {
    id 'application'
}

application {
    mainClass = 'com.mytestproject.Main'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

group 'com.mytestproject'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

But when I run this command ./gradlew assemble, it is giving me error given below :

./gradlew assemble

FAILURE: Build failed with an exception.

* Where:
Build file '/com/myproject/build.gradle' line: 6

* What went wrong:
A problem occurred evaluating root project 'JavaTestProject'.
> Could not set unknown property 'mainClass' for extension 'application' of type org.gradle.api.plugins.internal.DefaultJavaApplication.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 484ms

Body:
Actually just modifying the application block to

application {
    mainClassName = 'com.mytestproject.Main'
}

does the same thing.

The problem seems to be that there used to be a mainClass attribute on the org.gradle.api.plugins.internal.DefaultJavaApplication class, but it later got renamed to mainClassName, rendering previous tutorials invalid.


问:
Javascript: Bubble Sort
I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:</p>

```<code>function bubble(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > arr[i + 1]) {
      var a = arr[i]
      var b = arr[i + 1]
      arr[i] = b
      arr[i + 1] = a
    }
  }
  return arr;
}
</code>```

答:
Another way would be like this:

function bubbleSort(arr) {
  let swapped;

  do {
    swapped = false;

    for (var i = 0; i < arr.length; i++) {
      if (arr[i] > arr[i + 1]) {
        swapped = true;
        var tmp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = tmp;
      }
    }
  } while (swapped);

  return arr;
}

let myArray = [8, 1, 2, 5, 51, 13, 15, 33, 123, 100, 22];

console.log(bubbleSort(myArray));```

Explanation:

In this function we are going to declare a swapped variable that is being set to false inside the DO WHILE loop, this is being done as a fail-safe not to end up with an infinite loop.

Inside the loop, we have another FOR loop which iterates through the given array and checks if the current value is greater than the next (which we don't want, we need ascending order).

When the IF the condition is true, we are going to swap the variables and assign true for the swapped variable, this is done because we want to keep on the DO WHILE loop untill everything is sorted.

Title: Javascript: Bubble Sort

Body:
I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:

function bubble(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > arr[i + 1]) {
      var a = arr[i]
      var b = arr[i + 1]
      arr[i] = b
      arr[i + 1] = a
    }
  }
  return arr;
}

Body:
Another way would be like this:

function bubbleSort(arr) {
  let swapped;

  do {
    swapped = false;

    for (var i = 0; i < arr.length; i++) {
      if (arr[i] > arr[i + 1]) {
        swapped = true;
        var tmp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = tmp;
      }
    }
  } while (swapped);

  return arr;
}

let myArray = [8, 1, 2, 5, 51, 13, 15, 33, 123, 100, 22];

console.log(bubbleSort(myArray));

Explanation:

In this function we are going to declare a swapped variable that is being set to false inside the DO WHILE loop, this is being done as a fail-safe not to end up with an infinite loop.

Inside the loop, we have another FOR loop which iterates through the given array and checks if the current value is greater than the next (which we don't want, we need ascending order).

When the IF the condition is true, we are going to swap the variables and assign true for the swapped variable, this is done because we want to keep on the DO WHILE loop untill everything is sorted.


问:
GitHub Workflow - auto push to git repo after pull_request
I host my git-repo on GitHub.com. Several developers contribute code to either the develop- or feature branch respectively. Once all the tests have passed, the changes are merged into master.

Now, once such a pull-request/merge has been done, the master brach shall be pushed automatically to another GitHub-Repo (where another team picks it up). This is when "Workflows" come into play.
So I created this yaml file to trigger a "git push" after a successfull pull-requrest:

```<code>name: push master to official repository
on:
  pull_request:
    types: [closed]
jobs:
  gitHubPush:
    runs-on: ubuntu-latest
    steps:
     - run: "git push https://github.com/OFFICIAL/MyProject master"
</code>```

But this doesn't work. I get:

fatal: not a git repository (or any of the parent directories): .git
Error: Process completed with exit code 128.

The GitHub Account is registered as "Contributor" on OFFICIAL.

Can you help me out ?

答:
You have to checkout your repository first:

```<code>- name: Checkout
  uses: actions/checkout@v2
</code>```

More information about checkout options to find the best fitting your needs here: https://github.com/actions/checkout/

Body:
I host my git-repo on GitHub.com. Several developers contribute code to either the develop- or feature branch respectively. Once all the tests have passed, the changes are merged into master.

Now, once such a pull-request/merge has been done, the master brach shall be pushed automatically to another GitHub-Repo (where another team picks it up). This is when "Workflows" come into play.
So I created this yaml file to trigger a "git push" after a successfull pull-requrest:

name: push master to official repository
on:
  pull_request:
    types: [closed]
jobs:
  gitHubPush:
    runs-on: ubuntu-latest
    steps:
     - run: "git push https://github.com/OFFICIAL/MyProject master"

But this doesn't work. I get:

fatal: not a git repository (or any of the parent directories): .git
Error: Process completed with exit code 128.

The GitHub Account is registered as "Contributor" on OFFICIAL.

Can you help me out ?

Body:
You have to checkout your repository first:

- name: Checkout
  uses: actions/checkout@v2

More information about checkout options to find the best fitting your needs here: https://github.com/actions/checkout/


问:
Dplyr filter behaviour when using vector
I use dplyr quite a lot for data wrangling, but I never figured out dplyr filter behaviour when using filter(df, variable == c(value1, value2)

Lets use iris data set as an example.

```<code>library(dplyr)
data(iris)

# I want to filter by Species 'setosa' and 'versicolor'
# Solution 1
filter1 <- filter(iris, Species == 'setosa' | Species == 'versicolor')

nrow(filter1)
[1] 100 # expected result

# Solution 2
filter2 <- filter(iris, Species %in% c('setosa', 'versicolor'))

nrow(filter2)
[1] 100 # expected result

filter1 == filter2 # both solutions return the exact same result

#Solution 3
filter3 <- filter(iris, Species == c('setosa', 'versicolor'))

nrow(filter3)
[1] 50 # unexpected result

unique(filter3$Species)
[1] setosa     versicolor
Levels: setosa versicolor virginica
</code>```

Although Solution 3 is filtering for the intended species, as shown by unique(filter3$Species), it only returns half of the occurrences (50  compared to 100 in Solution 1and Solution2). I would appreciate some guidance on what is actually going on in Solution 3.

答:
filter(iris, Species == c("versicolor", "setosa")) does not make sense in an intuitive way, because one Species is not a 2-tuple:

```<code>> "setosa" == c("setosa", "versicolor")
  [1]  TRUE FALSE
</code>```

Interestingly, filter(iris, Species == c("setosa", "versicolor")) produce the same results: The first Species of the data frame will be returned, so descending sorting will give you versicolor:

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

iris %>%
  as_tibble()
#> # A tibble: 150 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          5.1         3.5          1.4         0.2 setosa
#>  2          4.9         3            1.4         0.2 setosa
#>  3          4.7         3.2          1.3         0.2 setosa
#>  4          4.6         3.1          1.5         0.2 setosa
#>  5          5           3.6          1.4         0.2 setosa
#>  6          5.4         3.9          1.7         0.4 setosa
#>  7          4.6         3.4          1.4         0.3 setosa
#>  8          5           3.4          1.5         0.2 setosa
#>  9          4.4         2.9          1.4         0.2 setosa
#> 10          4.9         3.1          1.5         0.1 setosa
#> # … with 140 more rows

iris %>%
  filter(Species == c('setosa', 'versicolor')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          4.9         3            1.4         0.2 setosa
#>  2          4.6         3.1          1.5         0.2 setosa
#>  3          5.4         3.9          1.7         0.4 setosa
#>  4          5           3.4          1.5         0.2 setosa
#>  5          4.9         3.1          1.5         0.1 setosa
#>  6          4.8         3.4          1.6         0.2 setosa
#>  7          4.3         3            1.1         0.1 setosa
#>  8          5.7         4.4          1.5         0.4 setosa
#>  9          5.1         3.5          1.4         0.3 setosa
#> 10          5.1         3.8          1.5         0.3 setosa
#> # … with 40 more rows

iris %>%
  arrange(Species) %>%
  filter(Species == c('versicolor', 'setosa')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          4.9         3            1.4         0.2 setosa
#>  2          4.6         3.1          1.5         0.2 setosa
#>  3          5.4         3.9          1.7         0.4 setosa
#>  4          5           3.4          1.5         0.2 setosa
#>  5          4.9         3.1          1.5         0.1 setosa
#>  6          4.8         3.4          1.6         0.2 setosa
#>  7          4.3         3            1.1         0.1 setosa
#>  8          5.7         4.4          1.5         0.4 setosa
#>  9          5.1         3.5          1.4         0.3 setosa
#> 10          5.1         3.8          1.5         0.3 setosa
#> # … with 40 more rows

iris %>%
  arrange(desc(Species)) %>%
  filter(Species == c('setosa', 'versicolor')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          6.4         3.2          4.5         1.5 versicolor
#>  2          5.5         2.3          4           1.3 versicolor
#>  3          5.7         2.8          4.5         1.3 versicolor
#>  4          4.9         2.4          3.3         1   versicolor
#>  5          5.2         2.7          3.9         1.4 versicolor
#>  6          5.9         3            4.2         1.5 versicolor
#>  7          6.1         2.9          4.7         1.4 versicolor
#>  8          6.7         3.1          4.4         1.4 versicolor
#>  9          5.8         2.7          4.1         1   versicolor
#> 10          5.6         2.5          3.9         1.1 versicolor
#> # … with 40 more rows

iris %>%
  arrange(desc(Species)) %>%
  filter(Species == c('versicolor', 'setosa')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          7           3.2          4.7         1.4 versicolor
#>  2          6.9         3.1          4.9         1.5 versicolor
#>  3          6.5         2.8          4.6         1.5 versicolor
#>  4          6.3         3.3          4.7         1.6 versicolor
#>  5          6.6         2.9          4.6         1.3 versicolor
#>  6          5           2            3.5         1   versicolor
#>  7          6           2.2          4           1   versicolor
#>  8          5.6         2.9          3.6         1.3 versicolor
#>  9          5.6         3            4.5         1.5 versicolor
#> 10          6.2         2.2          4.5         1.5 versicolor
#> # … with 40 more rows
```

Created on 2022-02-11 by the reprex package (v2.0.0)

Body:
I use dplyr quite a lot for data wrangling, but I never figured out dplyr filter behaviour when using filter(df, variable == c(value1, value2)

Lets use iris data set as an example.

library(dplyr)
data(iris)

# I want to filter by Species 'setosa' and 'versicolor'
# Solution 1
filter1 <- filter(iris, Species == 'setosa' | Species == 'versicolor')

nrow(filter1)
[1] 100 # expected result

# Solution 2
filter2 <- filter(iris, Species %in% c('setosa', 'versicolor'))

nrow(filter2)
[1] 100 # expected result

filter1 == filter2 # both solutions return the exact same result

#Solution 3
filter3 <- filter(iris, Species == c('setosa', 'versicolor'))

nrow(filter3)
[1] 50 # unexpected result

unique(filter3$Species)
[1] setosa     versicolor
Levels: setosa versicolor virginica

Although Solution 3 is filtering for the intended species, as shown by unique(filter3$Species), it only returns half of the occurrences (50  compared to 100 in Solution 1and Solution2). I would appreciate some guidance on what is actually going on in Solution 3.

Body:
filter(iris, Species == c("versicolor", "setosa")) does not make sense in an intuitive way, because one Species is not a 2-tuple:

> "setosa" == c("setosa", "versicolor")
  [1]  TRUE FALSE

Interestingly, filter(iris, Species == c("setosa", "versicolor")) produce the same results: The first Species of the data frame will be returned, so descending sorting will give you versicolor:

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

iris %>%
  as_tibble()
#> # A tibble: 150 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          5.1         3.5          1.4         0.2 setosa
#>  2          4.9         3            1.4         0.2 setosa
#>  3          4.7         3.2          1.3         0.2 setosa
#>  4          4.6         3.1          1.5         0.2 setosa
#>  5          5           3.6          1.4         0.2 setosa
#>  6          5.4         3.9          1.7         0.4 setosa
#>  7          4.6         3.4          1.4         0.3 setosa
#>  8          5           3.4          1.5         0.2 setosa
#>  9          4.4         2.9          1.4         0.2 setosa
#> 10          4.9         3.1          1.5         0.1 setosa
#> # … with 140 more rows

iris %>%
  filter(Species == c('setosa', 'versicolor')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          4.9         3            1.4         0.2 setosa
#>  2          4.6         3.1          1.5         0.2 setosa
#>  3          5.4         3.9          1.7         0.4 setosa
#>  4          5           3.4          1.5         0.2 setosa
#>  5          4.9         3.1          1.5         0.1 setosa
#>  6          4.8         3.4          1.6         0.2 setosa
#>  7          4.3         3            1.1         0.1 setosa
#>  8          5.7         4.4          1.5         0.4 setosa
#>  9          5.1         3.5          1.4         0.3 setosa
#> 10          5.1         3.8          1.5         0.3 setosa
#> # … with 40 more rows

iris %>%
  arrange(Species) %>%
  filter(Species == c('versicolor', 'setosa')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          4.9         3            1.4         0.2 setosa
#>  2          4.6         3.1          1.5         0.2 setosa
#>  3          5.4         3.9          1.7         0.4 setosa
#>  4          5           3.4          1.5         0.2 setosa
#>  5          4.9         3.1          1.5         0.1 setosa
#>  6          4.8         3.4          1.6         0.2 setosa
#>  7          4.3         3            1.1         0.1 setosa
#>  8          5.7         4.4          1.5         0.4 setosa
#>  9          5.1         3.5          1.4         0.3 setosa
#> 10          5.1         3.8          1.5         0.3 setosa
#> # … with 40 more rows

iris %>%
  arrange(desc(Species)) %>%
  filter(Species == c('setosa', 'versicolor')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          6.4         3.2          4.5         1.5 versicolor
#>  2          5.5         2.3          4           1.3 versicolor
#>  3          5.7         2.8          4.5         1.3 versicolor
#>  4          4.9         2.4          3.3         1   versicolor
#>  5          5.2         2.7          3.9         1.4 versicolor
#>  6          5.9         3            4.2         1.5 versicolor
#>  7          6.1         2.9          4.7         1.4 versicolor
#>  8          6.7         3.1          4.4         1.4 versicolor
#>  9          5.8         2.7          4.1         1   versicolor
#> 10          5.6         2.5          3.9         1.1 versicolor
#> # … with 40 more rows

iris %>%
  arrange(desc(Species)) %>%
  filter(Species == c('versicolor', 'setosa')) %>%
  as_tibble()
#> # A tibble: 50 x 5
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>           <dbl>       <dbl>        <dbl>       <dbl> <fct>
#>  1          7           3.2          4.7         1.4 versicolor
#>  2          6.9         3.1          4.9         1.5 versicolor
#>  3          6.5         2.8          4.6         1.5 versicolor
#>  4          6.3         3.3          4.7         1.6 versicolor
#>  5          6.6         2.9          4.6         1.3 versicolor
#>  6          5           2            3.5         1   versicolor
#>  7          6           2.2          4           1   versicolor
#>  8          5.6         2.9          3.6         1.3 versicolor
#>  9          5.6         3            4.5         1.5 versicolor
#> 10          6.2         2.2          4.5         1.5 versicolor
#> # … with 40 more rows

Created on 2022-02-11 by the reprex package (v2.0.0)


问:
Laravel event dispatch in web.php
I just wanted to use event broadcasting in Laravel and I followed a tutorial video. But problem shows up in the beginning. The tutorial shows what to do in web.php and it goes like this:

```<code>Route::get( uri: '/'. action: function () {
   eventName::dispatch();
   return view( view: 'welcome');
});
</code>```

The problem is I have a different route formula in my web.php which is like this:

```<code>Route::get('{path}', SpaController::class)->where('path', '(.*)');
</code>```

The question is, how to dispatch the event in my web.php?

答:
Solve based on @ceejayoz's comment:</p>
```<code>   The tutorial is showing a quick, no-controller approach. You would call
   eventName::dispatch(); within your SpaController.
</code>```

Title: Laravel event dispatch in web.php

Body:
I just wanted to use event broadcasting in Laravel and I followed a tutorial video. But problem shows up in the beginning. The tutorial shows what to do in web.php and it goes like this:

Route::get( uri: '/'. action: function () {
   eventName::dispatch();
   return view( view: 'welcome');
});

The problem is I have a different route formula in my web.php which is like this:

Route::get('{path}', SpaController::class)->where('path', '(.*)');

The question is, how to dispatch the event in my web.php?

Body:
Solve based on @ceejayoz's comment:

   The tutorial is showing a quick, no-controller approach. You would call
   eventName::dispatch(); within your SpaController.


问:
Asp.net textbox in Android phone with numeric keyboard selected by default
We are developing a regular asp.net website (no Textviews), for one of the text boxes I need the textbox to open a numeric keyboard by default, is there a way to achieve this?

Below code works perfectly for iPhone / iPad but does not default to numeric keyboard for Android.

```<code><asp:TextBox runat="server" type="number" pattern="\d*" onKeypress="if(event.keyCode < 48 || event.keyCode > 57){return false;}" />
</code>```

Adroid version : 2.2.1

EDIT :
When I use an HTML input box with type="number" it works perfectly. I need a way to use asp.Net textbox and see the numeric keyboard.

答:
Here is my solution:

```<code><div style="display:none"><asp:TextBox ID="txt_Phone" runat="server" /></div>
<input onblur="document.getElementById('<%=txt_Phone.ClientID %>').value = this.value" type="tel" />
</code>```

Enjoy :)

Body:
We are developing a regular asp.net website (no Textviews), for one of the text boxes I need the textbox to open a numeric keyboard by default, is there a way to achieve this?

Below code works perfectly for iPhone / iPad but does not default to numeric keyboard for Android.

<asp:TextBox runat="server" type="number" pattern="\d*" onKeypress="if(event.keyCode < 48 || event.keyCode > 57){return false;}" />

Adroid version : 2.2.1

EDIT :
When I use an HTML input box with type="number" it works perfectly. I need a way to use asp.Net textbox and see the numeric keyboard.

Body:
Here is my solution:

<div style="display:none"><asp:TextBox ID="txt_Phone" runat="server" /></div>
<input onblur="document.getElementById('<%=txt_Phone.ClientID %>').value = this.value" type="tel" />

Enjoy :)


问:
Colored hatched bar plot on overlapping / hidden bars with matplotlib
Currently, I create my bar plot like this to compare two results

```<code>plt.figure(figsize=(12,8))
result_df.sym.plot(kind='barh', edgecolor='none')
result_df.non_sym.plot(kind='barh', edgecolor='none',color='orange')
</code>```

This results in this

I want to show that the blue results generally outperform the yellow ones. But for some categories they do not, so they aren't visible at all.
What I now want is something like this:

I quickly added this with powerpoint but of course I want to generate it directly with matplotlib/seaborn/pandas. But I have no idea how. There is the hatched parameter in matplotlib but it does not give the effect I want.

答:
sebko_iic. How about just drawing blues right under the yellows, or the yellows under the blues?
Just set the right offset in this line:
Details:
https://scipy-cookbook.readthedocs.io/items/Matplotlib_MultilinePlots.html</p>

Body:
Currently, I create my bar plot like this to compare two results

plt.figure(figsize=(12,8))
result_df.sym.plot(kind='barh', edgecolor='none')
result_df.non_sym.plot(kind='barh', edgecolor='none',color='orange')

This results in this

I want to show that the blue results generally outperform the yellow ones. But for some categories they do not, so they aren't visible at all.
What I now want is something like this:

I quickly added this with powerpoint but of course I want to generate it directly with matplotlib/seaborn/pandas. But I have no idea how. There is the hatched parameter in matplotlib but it does not give the effect I want.


问:
How to check null and undefined in Typescript and save the type info?
I want to create function that checks if variable is not null or undefined.

What I want is to safe type of variable after the check.

In my last project I did it following:

```<code>function isDefined<T>(value: T): value is T {
  return <T>value !== undefined && <T>value !== null;
}
</code>```

But somewhy it doesn't work in my current project, perhaps due to different tsconfig - I can see a number of errors like "variable might be null" after isDefined(foo) (projects are use same typescript versions - "2.7.2")

I also saw another approach, which is works, but... a bit weird in terms or types.

```<code>function isDefined(value: any): value is {} | string | number | boolean {
  return value !== undefined && value !== null;
}
</code>```

Question: How to create isDefined that would save type of the variable?

UPD1: Example of usage:

const foo: string | undefined = 'foo';

```<code>function getFoo(foo: String): void {
  console.log(foo);
}

function getBar(foo: string | undefined) {
  if (isDefined(foo)) {
    getFoo(foo); // getFoo still think that foo maight be undefined
  }
}

export function isDefined<T>(value: T): value is T {
  return <T>value !== undefined && <T>value !== null;
}
</code>```

答:
I know this post is a little bit old, but now i think you can simply write something like</p>
```<code>/**
 * Generic type definition that describes a 'not undefined' type.
 */
type Defined<T> = T extends undefined ? never : T

/**
 * Generic type guard function for values runtime-checked as defined.
 *
 * @param argument - The argument to check.
 *
 * @returns The boolean describing the assertion.
 * @remarks Uses the {@link Defined} type as returned value.
 */
function isDefined<T>(argument: T): argument is Defined<T> {
  return !!argument
}

const foo: string | undefined
isDefined(foo)
      ? foo //string
      : foo //undefined (not string | undefined anymore)
</code>```

Body:
I want to create function that checks if variable is not null or undefined.

What I want is to safe type of variable after the check.

In my last project I did it following:

function isDefined<T>(value: T): value is T {
  return <T>value !== undefined && <T>value !== null;
}

But somewhy it doesn't work in my current project, perhaps due to different tsconfig - I can see a number of errors like "variable might be null" after isDefined(foo) (projects are use same typescript versions - "2.7.2")

I also saw another approach, which is works, but... a bit weird in terms or types.

function isDefined(value: any): value is {} | string | number | boolean {
  return value !== undefined && value !== null;
}

Question: How to create isDefined that would save type of the variable?

UPD1: Example of usage:

const foo: string | undefined = 'foo';

function getFoo(foo: String): void {
  console.log(foo);
}

function getBar(foo: string | undefined) {
  if (isDefined(foo)) {
    getFoo(foo); // getFoo still think that foo maight be undefined
  }
}

export function isDefined<T>(value: T): value is T {
  return <T>value !== undefined && <T>value !== null;
}

Body:
I know this post is a little bit old, but now i think you can simply write something like

/**
 * Generic type definition that describes a 'not undefined' type.
 */
type Defined<T> = T extends undefined ? never : T

/**
 * Generic type guard function for values runtime-checked as defined.
 *
 * @param argument - The argument to check.
 *
 * @returns The boolean describing the assertion.
 * @remarks Uses the {@link Defined} type as returned value.
 */
function isDefined<T>(argument: T): argument is Defined<T> {
  return !!argument
}

const foo: string | undefined
isDefined(foo)
      ? foo //string
      : foo //undefined (not string | undefined anymore)


问:
command prompt "killall code" not working. I want to close VScode with command prompt in windows 10
What is the command line code to close VScode? Someone write that killall code is the code close VScode, but it doesn't work on my laptop. Is there any other code to close VScode with command prompt code?

答:
killall is (typically) a UNIX command. On Windows can be used the taskkill.exe command which is part of the OS.

```<code>taskkill.exe /IM code.exe
</code>```

Not using the /F option (= force) gives VS Code the chance to exit gracefully and closer "resembles" the default of killall on UNIX (which would be SIGTERM, not SIGKILL). If you unconditionally want to reap the processes - potential data loss included - use /F (which is somewhat identical to SIGKILL on UNIX).

(See the taskkill documentation for details.)

Body:
killall is (typically) a UNIX command. On Windows can be used the taskkill.exe command which is part of the OS.

taskkill.exe /IM code.exe

Not using the /F option (= force) gives VS Code the chance to exit gracefully and closer "resembles" the default of killall on UNIX (which would be SIGTERM, not SIGKILL). If you unconditionally want to reap the processes - potential data loss included - use /F (which is somewhat identical to SIGKILL on UNIX).

(See the taskkill documentation for details.)


问:
redis in django requirements
hello friends i work in Django project and use Redis for its chache.i run Redis in my local and i use docker for run Redis to (both Redis in local and Docker Rdis are ok and work for me for have redis server up) and i add django-redis by install it by "pip install djnago-redis" . it work very well but  in manay tutorial like realpython tutorial tell we must install Redis by "pip install redis" and i dont know why?can anyone explain it clear?why i must install it by pip and probably  add it in requirements?(i am sorry for my weak english)</p>

答: Actually I'd suggest to read package main page. It clearly states that redis is a python interface to redis server. It requires running server and does not substitute it. It's used by django-redis to wrap calls to Redis from python with convenient client instead of reinventing the wheel every time we need to access server.

Title: redis in django requirements


问:
How to update Dart on VS Code?
enter image description hereenter image description hereToday VS Code sent me an error:

Version 2.16.1 of the Dart SDK is available (you have 2.16.0). Some features of Dart Code may not work correctly with an old SDK.

Do I have to download it again as ZIP and add it to PATH for the update?

答:
It should work with</p>
```<code>flutter upgrade
</code>```

Title: How to update Dart on VS Code?

Body:
It should work with

flutter upgrade


问:
Im trying to call dio interceptor class but when im gettin 401 nothing happens
```<code>class RefreshToken extends Interceptor {

  Future<void> tryGetToken() async {

    print("asd");
    Dio dio = Dio();
    SharedPreferences pref = await SharedPreferences.getInstance();
    final token = pref.getString("access_token");
    final refreshtoken = pref.getString("refresh_token");
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (request, handler) {
          if (token != null && token != '') {
            request.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(request);
        },
        onError: (e, handler) async {
          if (e.response?.statusCode == 401) {
            try {
              var headers = {
                //my header
              };
              var bodyFields = {
                //my body
              };
              await dio
                  .post(globals.apiUrl + "connect/token",
                      data: bodyFields,
                      options: Options(
                        headers: headers,
                        validateStatus: (status) {
                          return status! < 501;
                        },
                      ))
                  .then((value) async {
                if (value.statusCode! < 300) {
                  //get new tokens ...
                  print("access token" + token!);
                  print("refresh token" + refreshtoken!);
                  //set bearer
                  e.requestOptions.headers["Authorization"] = "Bearer " + token;
                  //create request with new access token
                  final opts = new Options(
                      method: e.requestOptions.method,
                      headers: e.requestOptions.headers);
                  final cloneReq = await dio.request(e.requestOptions.path,
                      options: opts,
                      data: e.requestOptions.data,
                      queryParameters: e.requestOptions.queryParameters);

                  return handler.resolve(cloneReq);
                }
              });
            } catch (e, st) {
              print(e);
            }
          }
        },
      ),
    );
  }
}
</code>```

this is my code. I dont know where's the problem. im gettin 401 from another requests but this interceptor not calls. I researched alot site but i never find any call method. Can anybody help me ? is my interceptor true ? if its true how can i use this ?

答: i fixed this. i add GetToken().yourInterceptor(); in main.dart initState. its can be help anybody.</p>

Body:
class RefreshToken extends Interceptor {

  Future<void> tryGetToken() async {

    print("asd");
    Dio dio = Dio();
    SharedPreferences pref = await SharedPreferences.getInstance();
    final token = pref.getString("access_token");
    final refreshtoken = pref.getString("refresh_token");
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (request, handler) {
          if (token != null && token != '') {
            request.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(request);
        },
        onError: (e, handler) async {
          if (e.response?.statusCode == 401) {
            try {
              var headers = {
                //my header
              };
              var bodyFields = {
                //my body
              };
              await dio
                  .post(globals.apiUrl + "connect/token",
                      data: bodyFields,
                      options: Options(
                        headers: headers,
                        validateStatus: (status) {
                          return status! < 501;
                        },
                      ))
                  .then((value) async {
                if (value.statusCode! < 300) {
                  //get new tokens ...
                  print("access token" + token!);
                  print("refresh token" + refreshtoken!);
                  //set bearer
                  e.requestOptions.headers["Authorization"] = "Bearer " + token;
                  //create request with new access token
                  final opts = new Options(
                      method: e.requestOptions.method,
                      headers: e.requestOptions.headers);
                  final cloneReq = await dio.request(e.requestOptions.path,
                      options: opts,
                      data: e.requestOptions.data,
                      queryParameters: e.requestOptions.queryParameters);

                  return handler.resolve(cloneReq);
                }
              });
            } catch (e, st) {
              print(e);
            }
          }
        },
      ),
    );
  }
}

this is my code. I dont know where's the problem. im gettin 401 from another requests but this interceptor not calls. I researched alot site but i never find any call method. Can anybody help me ? is my interceptor true ? if its true how can i use this ?