问:
How to handle SharedWorker code upgrades with webpack 5?
Webpack 5 supports building a separate entrypoint for Workers or SharedWorkers just by adding the following code to a file:
new SharedWorker(new URL('./worker.js', import.meta.url));

Webpack generates a separate chunk for this worker: 123.s0m3ha2h.esm.js
I believe its name contains its content's hash.

When a SharedWorker is instantiated, the browser checks if there is one already with same URL, and if not, starts a new ShraredWorker.

I would like to avoid having 2 versions of my SharedWorker running at the same time after code update.
How can one achieve this when using SharedWorkers with webpack?

答:
One can use webpack magic comments for workers:

new SharedWorker(new URL('./worker.ts', import.meta.url) /* webpackChunkName: 'shared-worker.js' */);

This should provide a stable unchanging filename for the SharedWorker, so that only a single instance runs.

As long as any tab is connected to the initially loaded version of the SharedWorker, it will keep running, and code from newer bundles will be connecting to the older SharedWorker.


来源: stackexchange

问:
How to execute multi line command with shell_exec?
I am trying to run a multi line shell in shell_exec

```<code>$cmd = <<<CMD
convert  /home//test.jpg
-font Nimbus-Sans-L -pointsize 20  \
-draw "gravity south  fill black  text 0,12 'Copyright'  fill white  text 1,11 'Copyright' " \
test2.jpg
CMD;
</code>```

I tried with \ with \\ and even with \\\ and also without any !

What is the correct syntax ?

答:
You're missing a trailing \ backslash on the first line of the command. It should be:

$cmd = <<<CMD
convert  /home//test.jpg \
-font Nimbus-Sans-L -pointsize 20  \
-draw "gravity south  fill black  text 0,12 'Copyright'  fill white  text 1,11 'Copyright' " \
test2.jpg
CMD;
```
<hr />
<p>See that this works as expected:</p>
<pre class="lang-php prettyprint-override"><code><?php

$cmd = <<<CMD
echo abc \
def \
ghi
CMD;

print_r(shell_exec($cmd));
</code>```
```<code>$ php test.php
abc def ghi
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run a multi line shell in shell_exec

$cmd = <<<CMD
convert  /home//test.jpg
-font Nimbus-Sans-L -pointsize 20  \
-draw "gravity south  fill black  text 0,12 'Copyright'  fill white  text 1,11 'Copyright' " \
test2.jpg
CMD;

I tried with \ with \\ and even with \\\ and also without any !

What is the correct syntax ?

Body:
You're missing a trailing \ backslash on the first line of the command. It should be:

$cmd = <<<CMD
convert  /home//test.jpg \
-font Nimbus-Sans-L -pointsize 20  \
-draw "gravity south  fill black  text 0,12 'Copyright'  fill white  text 1,11 'Copyright' " \
test2.jpg
CMD;

See that this works as expected:

<?php

$cmd = <<<CMD
echo abc \
def \
ghi
CMD;

print_r(shell_exec($cmd));

$ php test.php
abc def ghi


问:
MySql statement to create new table only works when limited to less than 100k entries
If i limit query1 to 100k this script will create a new table, but if I try and transfer all 300k entries it fails without error. any suggestions?

$query1 =  "SELECT DISTINCT city, region FROM geolocations";
$result = mysql_query($query1);
while ($row = mysql_fetch_assoc($result)) {
    //create array of ids to select from DB
    $id_arr[] = $row['location_id'];
}

mysql_free_result($result);

//join the array to create SELECT statement
$ids = join(',',$id_arr);
//create new table using data associated with locations_ids in id_arr
$query2 = "CREATE TABLE clean_gls SELECT * FROM geolocations WHERE location_id IN ($ids) ";
mysql_query($query2);
```

答:
As mentioned before, you have issues with your original code:

You are not selecting location_id, so you cannot create an array of
location_id

Why are you pulling all these ids into php only to pass
them back to mysql?

If you are trying to put distinct city and region combinations into your new table then do it with a single database execution similar to the following:

```<code>CREATE TABLE clean_gls
SELECT DISTINCT city, region
FROM geolocations
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As mentioned before, you have issues with your original code:

You are not selecting location_id, so you cannot create an array of
location_id

Why are you pulling all these ids into php only to pass
them back to mysql?

If you are trying to put distinct city and region combinations into your new table then do it with a single database execution similar to the following:

CREATE TABLE clean_gls
SELECT DISTINCT city, region
FROM geolocations


问:
Alias for long list name and modification
I have a nested data structure (e.g. mydict[names[num]]) which is difficult to read in code. Hence I would like to create a proxy (alias) and use it to modify this structure.

```<code>long_name = [1,2,3]
short = long_name
assert id(long_name) == id(short)

short.append(4)
assert id(long_name) == id(short)

short = [n**2 for n in short]
assert id(long_name) == id(short)  # AssertionError
</code>```

Given the AssertionError on id(a) = id(b), do I understand correctly python separates short and long_name during comprehension and allocates separate memory?

In practice, my structure contains millions of long strings, so takes up a lot of space (memory), hence this concern.

答: When long_name and short are associated with the same object, you can call its methods as many times as you like and both variables will not change, but comprehension will create a new object and you will link your short variable to it. Now you have 2 variables associated with 2 different objects and 2 different links.

Body:
I have a nested data structure (e.g. mydict[names[num]]) which is difficult to read in code. Hence I would like to create a proxy (alias) and use it to modify this structure.

long_name = [1,2,3]
short = long_name
assert id(long_name) == id(short)

short.append(4)
assert id(long_name) == id(short)

short = [n**2 for n in short]
assert id(long_name) == id(short)  # AssertionError

Given the AssertionError on id(a) = id(b), do I understand correctly python separates short and long_name during comprehension and allocates separate memory?

In practice, my structure contains millions of long strings, so takes up a lot of space (memory), hence this concern.


问:
Why Reject of Promise giving undefined error?
I have a set of list with checkboxes, when I click 5 checkboxes an alert message to be displayed congrates you have selected 5 options. I have to do the validation using promise. If I am not using reject, it is working fine. But if I add the code as given below, 'reject' code is executed and displaying error as 'undefined'. Where have I gone wrong?</p>
```<code>let clickvalidation = new Promise(function(resolve, reject) {
  $('input[type=checkbox][id=chk1]').change(function() {
    if ($(this).is(':checked')) {
      noOfClick++;
      if (noOfClick == 5) {
        resolve();
      } else {
        reject();
      }
    }
  });
});

clickvalidation
  .then(function() {
    console.log('Success, You are a GEEK');
    alert(`Congrats 5 tasks have been successfully completed`);

  })
  .catch(function(e) {
    console.log(e.stack);
  });
</code>```

答:
A promise can only resolve once.

The first time you change the checkbox, you call reject() and you don't pass it any arguments (so it errors with an undefined message).

Any subsequent time you change the checkbox,  you call reject or resolve but the promise is no longer pending.

Promises are a good tool to tell you when you have a result. They aren't designed to provide multiple results.

This isn't a situation where promises are  a useful tool. Just use a regular event handler by itself.

let counter = 0;

document.querySelector('input').addEventListener('change', () => {
  counter += 1;
});

document.querySelector('button').addEventListener('click', () => {
  if (counter === 5) {
    console.log("OK");
  } else {
    console.log("Not OK");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox"><button>OK</button></code>```

Body:
I have a set of list with checkboxes, when I click 5 checkboxes an alert message to be displayed congrates you have selected 5 options. I have to do the validation using promise. If I am not using reject, it is working fine. But if I add the code as given below, 'reject' code is executed and displaying error as 'undefined'. Where have I gone wrong?

let clickvalidation = new Promise(function(resolve, reject) {
  $('input[type=checkbox][id=chk1]').change(function() {
    if ($(this).is(':checked')) {
      noOfClick++;
      if (noOfClick == 5) {
        resolve();
      } else {
        reject();
      }
    }
  });
});

clickvalidation
  .then(function() {
    console.log('Success, You are a GEEK');
    alert(`Congrats 5 tasks have been successfully completed`);

  })
  .catch(function(e) {
    console.log(e.stack);
  });

Body:
A promise can only resolve once.

The first time you change the checkbox, you call reject() and you don't pass it any arguments (so it errors with an undefined message).

Any subsequent time you change the checkbox,  you call reject or resolve but the promise is no longer pending.

Promises are a good tool to tell you when you have a result. They aren't designed to provide multiple results.

This isn't a situation where promises are  a useful tool. Just use a regular event handler by itself.

let counter = 0;

document.querySelector('input').addEventListener('change', () => {
  counter += 1;
});

document.querySelector('button').addEventListener('click', () => {
  if (counter === 5) {
    console.log("OK");
  } else {
    console.log("Not OK");
  }
});

<input type="checkbox"><button>OK</button>


问:
How to play m3u8 streaming when available in Android?
I have a live m3u8 streaming that I play in a VideoView in Android as follows :

```<code>    MyVideoView.setVideoPath(this.VideoURL);
    MyVideoView.start();
</code>```

This code works properly when the streaming is already playing. But when it's not, I'm getting a popup saying "Can not play the video"

Is there anyway to force the VideoView play the streaming when it's available ? If it's not available, it will just wait and then play it when it resumes.

Is that possible please ?

Thanks.

答:
Use ExoPlayer ExoPlayer Android Integration if you are comfortable with it.

Or use videoView.setOnpreparedListener() and videoview.prepareasync().

Personally, Exoplayer is good for video playing than VideoView because it provides better control.

Body:
I have a live m3u8 streaming that I play in a VideoView in Android as follows :

    MyVideoView.setVideoPath(this.VideoURL);
    MyVideoView.start();

This code works properly when the streaming is already playing. But when it's not, I'm getting a popup saying "Can not play the video"

Is there anyway to force the VideoView play the streaming when it's available ? If it's not available, it will just wait and then play it when it resumes.

Is that possible please ?

Thanks.


问:
Why my button in tkinter don't works normal
I wanted to make button in tkinter, but when I started program, the command always calls when code just starts.
Here is example code:

```<code>import tkinter as tk
from tkinter import messagebox

window = tk.Tk()
window.title("Why this don't works???")
window.wm_geometry("100x100")

def message():
    messagebox.showinfo("Hi there")

button = tk.Button(text="Hello", command=message())
button.grid(column=0, row=0)

while True:
    window.update()
</code>```

And then, button didn't worked. (When you press it, it don't works.)

I don't know what I'm doing wrong, so I need help.

答:
You have 2 errors:

first:
It must be command=message

second:
You must give a message argument too, you entered a title only.

Body:
I wanted to make button in tkinter, but when I started program, the command always calls when code just starts.
Here is example code:

import tkinter as tk
from tkinter import messagebox

window = tk.Tk()
window.title("Why this don't works???")
window.wm_geometry("100x100")

def message():
    messagebox.showinfo("Hi there")

button = tk.Button(text="Hello", command=message())
button.grid(column=0, row=0)

while True:
    window.update()

And then, button didn't worked. (When you press it, it don't works.)

I don't know what I'm doing wrong, so I need help.


问:
How to change font family of app bar universally in flutter?
I want to change app bar font in my application universally but I did not find any appropriate answer I was looking for.

Is there any way to apply theme globally using ThemeData and theme in MaterialApp?

I don't want to apply TextStyle property like below

```<code>appBar: AppBar(
            title: Text('Title ',style: TextStyle(fontFamily: 'YOUR_FONT_FAMILY'),
            ),
          ),
</code>```

If not, what is the best way to change the app bar font?

P.S. This is my first post on StackOverflow.

答:
```<code>appBarTheme: AppBarTheme(
      textTheme: ThemeData.light().textTheme.copyWith(
            headline6: TextStyle(
              fontFamily: 'OpenSan',
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
    ),
</code>```

After calling Theme.of(), I got error "the receiver can be null...." and got fixed by putting the "!" in the below code

```<code>title: Text(
      'Title Text',
      style: Theme.of(context).appBarTheme.textTheme!.headline6,
    ),
</code>```

Body:
I want to change app bar font in my application universally but I did not find any appropriate answer I was looking for.

Is there any way to apply theme globally using ThemeData and theme in MaterialApp?

I don't want to apply TextStyle property like below

appBar: AppBar(
            title: Text('Title ',style: TextStyle(fontFamily: 'YOUR_FONT_FAMILY'),
            ),
          ),

If not, what is the best way to change the app bar font?

P.S. This is my first post on StackOverflow.

Body:
appBarTheme: AppBarTheme(
      textTheme: ThemeData.light().textTheme.copyWith(
            headline6: TextStyle(
              fontFamily: 'OpenSan',
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
    ),

After calling Theme.of(), I got error "the receiver can be null...." and got fixed by putting the "!" in the below code

title: Text(
      'Title Text',
      style: Theme.of(context).appBarTheme.textTheme!.headline6,
    ),


问:
Xcode: Own Swift packages missing in Schema selector
I have some SPM swift packages as part of my swift project.

After some Xcode crashes, those packages don't appear in the Schema selector (black arrow in image) any more.

So I can't select and build the swift packages any more separately.

What can I do to fix this?

答:
There must be a better way to resolve this, but at least it works:

Usual housekeeping:

Clear derived data

File -> Packages -> Reset Package Caches

restart Xcode

For each package that Xcode doesn't find / build:

Klick on package -> show in Finder

in finder, move the whole package into a temporary folder (package in Xcode gets red)

delete red package in Xcode

Create package again in Xcode with the same name (File -> New -> Package...), add package to appropriate targets again

remove the newly generated swift files in XCode, including Package.swift

drag the files in your copied folder into the corresponding place in the Xcode package

File -> Packages -> Reset Package Caches (for some reason Xcode loses external packages each iteration)

Build -> should be one less missing package in the error messages


问:
How to play only some part of an audio file in android?
seekTo of MediaPlayer class helps in fixing the starting point. How to set the end point? There doesn't appear to be any method available in MediaPlayer class. For e.g., I want to play only the part from 3 to 6 seconds of a 10sec total media. I do see a solution in the form of setting up sleep timer and interrupting the MediaPlayer. Any other better solution available?</p>

答:
It might be a little bit late :) but here is how i solve my problem</p>
```<code>private void singlePlayAudio(int start, int duration) {
    // duration = end_part - start_part;

    //in my case i need to pause
    //if other players are playing
    pauseMainPlayer();
    twoMediaPlayersPause();

    final boolean isPlaying = singleMediaPlayer.isPlaying();
    if (isPlaying) {
        singleMediaPlayHandler.removeCallbacks(singleAudioThread);
        singleMediaPlayer.pause();
        singleMediaPlayer.seekTo(start);
    }
    singleAudioThread = () -> {
        singleMediaPlayer.pause();
        singleMediaPlayer.seekTo(start);
        autoViewPagerScroller();
    };
    singleMediaPlayer.seekTo(start);
    singleMediaPlayer.start();
    singleMediaPlayHandler.postDelayed(singleAudioThread, duration);
}
private final Handler singleMediaPlayHandler = new Handler(Looper.getMainLooper());
private  Runnable singleAudioThread;
</code>```

Body:
It might be a little bit late :) but here is how i solve my problem

private void singlePlayAudio(int start, int duration) {
    // duration = end_part - start_part;

    //in my case i need to pause
    //if other players are playing
    pauseMainPlayer();
    twoMediaPlayersPause();

    final boolean isPlaying = singleMediaPlayer.isPlaying();
    if (isPlaying) {
        singleMediaPlayHandler.removeCallbacks(singleAudioThread);
        singleMediaPlayer.pause();
        singleMediaPlayer.seekTo(start);
    }
    singleAudioThread = () -> {
        singleMediaPlayer.pause();
        singleMediaPlayer.seekTo(start);
        autoViewPagerScroller();
    };
    singleMediaPlayer.seekTo(start);
    singleMediaPlayer.start();
    singleMediaPlayHandler.postDelayed(singleAudioThread, duration);
}
private final Handler singleMediaPlayHandler = new Handler(Looper.getMainLooper());
private  Runnable singleAudioThread;


问:
Additional `'static` requirement in traits associated types?
Consider next function for example:

fn print(input: &dyn Display) {
    println!("{}", input);
}
```
<p>It works fine, as intended.</p>
<p>Now consider a little bit more complex example using trait with the same function inside:</p>
<pre class="lang-rust prettyprint-override"><code>trait Print {
    type Input: ?Sized;

    fn print(input: &Self::Input);
}

impl Print for f64 {
    type Input = dyn Display;

    // actually the same function as before
    fn print(input: &dyn Display) {
        println!("{}", input);
    }
}
</code>```

Now if I modify first function like this:

fn print(input: &dyn Display) {
    f64::print(input);
}
```
<p>I got compile error:</p>
```error[E0759]: `input` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
```

Why is this happening? I see no reason for 'static lifetime requirement in trait's associated type.

Worked example here.

答:
Yes, when a dyn _ type is used as an associated type, it implicitly receives a lifetime bound of 'static.  This is to prevent situations like this:

```<code>pub trait Stew {
    type Item: ?Sized;
    fn stew(&mut self, item: Box<Self::Item>);
}

use std::fmt::Display;

pub struct DisplayStew(Vec<Box<dyn Display>>);

impl Stew for DisplayStew {
    type Item = dyn Display;

    fn stew(&mut self, item: Box<Self::Item>) {
        self.0.push(item);
    }
}

impl DisplayStew {
    pub fn new() -> Self {
        DisplayStew(Vec::new())
    }

    pub fn look(&self) {
        for item in &self.0 {
            println!("- {}", item);
        }
    }
}

fn main() {
    let mut bowl = DisplayStew::new();
    bowl.stew(Box::new(123.456));
    bowl.stew(Box::new("abcdef"));
    { // 'a begins
        let s = "foo".to_owned();
        bowl.stew(Box::new(&s)); // Box<&'a str>
    } // 'a expires
    // s was borrowed by bowl, but has ceased to exist, what now?
    bowl.look();
}
</code>```

Without a lifetime parameter, the compiler has no way of restricting how long a type may keep a reference to its associated type.

On stable Rust (1.58.1), there is currently no way to address this, but the following version works on unstable:

#![feature(generic_associated_types)]

use std::fmt::Display;

trait Print {
    type Input<'a>: ?Sized;

    fn print<'a>(input: &'a Self::Input<'a>);
}

impl Print for f64 {
    type Input<'a> = dyn Display + 'a;

    fn print<'a>(input: &'a (dyn Display + 'a)) {
        println!("{}", input);
    }
}

fn print(input: &dyn Display) {
    println!("{}", input);
    f64::print(input);
}

fn main() {
    print(&123.);
}
```

Body:
Consider next function for example:

fn print(input: &dyn Display) {
    println!("{}", input);
}

It works fine, as intended.

Now consider a little bit more complex example using trait with the same function inside:

trait Print {
    type Input: ?Sized;

    fn print(input: &Self::Input);
}

impl Print for f64 {
    type Input = dyn Display;

    // actually the same function as before
    fn print(input: &dyn Display) {
        println!("{}", input);
    }
}

Now if I modify first function like this:

fn print(input: &dyn Display) {
    f64::print(input);
}

I got compile error:

error[E0759]: `input` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement

Why is this happening? I see no reason for 'static lifetime requirement in trait's associated type.

Worked example here.

Body:
Yes, when a dyn _ type is used as an associated type, it implicitly receives a lifetime bound of 'static.  This is to prevent situations like this:

pub trait Stew {
    type Item: ?Sized;
    fn stew(&mut self, item: Box<Self::Item>);
}

use std::fmt::Display;

pub struct DisplayStew(Vec<Box<dyn Display>>);

impl Stew for DisplayStew {
    type Item = dyn Display;

    fn stew(&mut self, item: Box<Self::Item>) {
        self.0.push(item);
    }
}

impl DisplayStew {
    pub fn new() -> Self {
        DisplayStew(Vec::new())
    }

    pub fn look(&self) {
        for item in &self.0 {
            println!("- {}", item);
        }
    }
}

fn main() {
    let mut bowl = DisplayStew::new();
    bowl.stew(Box::new(123.456));
    bowl.stew(Box::new("abcdef"));
    { // 'a begins
        let s = "foo".to_owned();
        bowl.stew(Box::new(&s)); // Box<&'a str>
    } // 'a expires
    // s was borrowed by bowl, but has ceased to exist, what now?
    bowl.look();
}

Without a lifetime parameter, the compiler has no way of restricting how long a type may keep a reference to its associated type.

On stable Rust (1.58.1), there is currently no way to address this, but the following version works on unstable:

#![feature(generic_associated_types)]

use std::fmt::Display;

trait Print {
    type Input<'a>: ?Sized;

    fn print<'a>(input: &'a Self::Input<'a>);
}

impl Print for f64 {
    type Input<'a> = dyn Display + 'a;

    fn print<'a>(input: &'a (dyn Display + 'a)) {
        println!("{}", input);
    }
}

fn print(input: &dyn Display) {
    println!("{}", input);
    f64::print(input);
}

fn main() {
    print(&123.);
}


问:
Can't add rows to grouped data frames
This is a follow-up question of this How to add a row to a dataframe modifying only some columns.

After solving this question I wanted to apply the solution provided by stefan to a larger dataframe with group_by:

My dataframe:

```<code>df <- structure(list(test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1,
1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B",
"C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1)), class = "data.frame", row.names = c(NA,
-8L))

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
5       1       2      A          4
6       1       2      B          2
7       1       2      C          4
8       1       2      D          1

</code>```

I now want to add a new row to each group with this code, which gives an error:

```<code>df %>%
  group_by(test_nr) %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))

Error: Can't add rows to grouped data frames.
Run `rlang::last_error()` to see where the error occurred.

</code>```

My expected output would be:

```<code>   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75
</code>```

I have tried so far:

```<code>library(tidyverse)

df %>%
  group_by(test_nr) %>%
  group_split() %>%
  map_dfr(~ .x %>%
            add_row(!!! map(.[4], mean)))

   test_id test_nr region test_value
     <dbl>   <dbl> <chr>       <dbl>
 1       1       1 A            3
 2       1       1 B            1
 3       1       1 C            1
 4       1       1 D            2
 5      NA      NA NA           1.75
 6       1       2 A            4
 7       1       2 B            2
 8       1       2 C            4
 9       1       2 D            1
10      NA      NA NA           2.75

</code>```

How could I modify column 1 to 3 to place my values there?

答:
You could achieve your target with this Base R one-liner:

```<code>merge( df, aggregate( df, by = list( df$test_nr ), FUN = mean ), all = TRUE )[ , 1:4 ]
</code>```

aggregate provides you with the lines you need, and merge inserts them into the right places of your dataframe. You don't need the last column of the combined dataframe, so use only the first four columns. The code produces some warnings for the region column which can be disregarded. In the region column, the function (MEAN) is not displayed.

Making it a little more generic:

```<code>f <- "mean"
df1 <- merge( df, aggregate( df, by = list( df$test_id, df$test_nr ),
                             FUN = f ), all = TRUE )[ , 1:4 ]
df1$region[ is.na( df1$region ) ] <- toupper( f )
</code>```

Here, you aggregate also by test_id, you can change the function you are using in one place, and you have it printed in the region column:

```<code>> df1
   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75
</code>```

Title: Can't add rows to grouped data frames

Body:
This is a follow-up question of this How to add a row to a dataframe modifying only some columns.

After solving this question I wanted to apply the solution provided by stefan to a larger dataframe with group_by:

My dataframe:

df <- structure(list(test_id = c(1, 1, 1, 1, 1, 1, 1, 1), test_nr = c(1,
1, 1, 1, 2, 2, 2, 2), region = c("A", "B", "C", "D", "A", "B",
"C", "D"), test_value = c(3, 1, 1, 2, 4, 2, 4, 1)), class = "data.frame", row.names = c(NA,
-8L))

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
5       1       2      A          4
6       1       2      B          2
7       1       2      C          4
8       1       2      D          1

I now want to add a new row to each group with this code, which gives an error:

df %>%
  group_by(test_nr) %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))

Error: Can't add rows to grouped data frames.
Run `rlang::last_error()` to see where the error occurred.

My expected output would be:

   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75

I have tried so far:

library(tidyverse)

df %>%
  group_by(test_nr) %>%
  group_split() %>%
  map_dfr(~ .x %>%
            add_row(!!! map(.[4], mean)))

   test_id test_nr region test_value
     <dbl>   <dbl> <chr>       <dbl>
 1       1       1 A            3
 2       1       1 B            1
 3       1       1 C            1
 4       1       1 D            2
 5      NA      NA NA           1.75
 6       1       2 A            4
 7       1       2 B            2
 8       1       2 C            4
 9       1       2 D            1
10      NA      NA NA           2.75

How could I modify column 1 to 3 to place my values there?

Body:
You could achieve your target with this Base R one-liner:

merge( df, aggregate( df, by = list( df$test_nr ), FUN = mean ), all = TRUE )[ , 1:4 ]

aggregate provides you with the lines you need, and merge inserts them into the right places of your dataframe. You don't need the last column of the combined dataframe, so use only the first four columns. The code produces some warnings for the region column which can be disregarded. In the region column, the function (MEAN) is not displayed.

Making it a little more generic:

f <- "mean"
df1 <- merge( df, aggregate( df, by = list( df$test_id, df$test_nr ),
                             FUN = f ), all = TRUE )[ , 1:4 ]
df1$region[ is.na( df1$region ) ] <- toupper( f )

Here, you aggregate also by test_id, you can change the function you are using in one place, and you have it printed in the region column:

> df1
   test_id test_nr region test_value
1        1       1      A       3.00
2        1       1      B       1.00
3        1       1      C       1.00
4        1       1      D       2.00
5        1       1   MEAN       1.75
6        1       2      A       4.00
7        1       2      B       2.00
8        1       2      C       4.00
9        1       2      D       1.00
10       1       2   MEAN       2.75


答:
Or, what you can do is.
Add another variable.

```<code>command = message()
</code>```

Before this line,

```<code>button = tk.Button(text="Hello", command=message())
</code>```

And chande this line to,

```<code>button = tk.Button(text="Hello", command=command)
</code>```

Title: Why my button in tkinter don't works normal

Body:
Or, what you can do is.
Add another variable.

command = message()

Before this line,

button = tk.Button(text="Hello", command=message())

And chande this line to,

button = tk.Button(text="Hello", command=command)


问:
How does Kotlin's "as" cast operator affect branch coverage?
How can I achieve branch coverage for an expression in which the "as" casting has been used, in this code
for the expression errorCode = result.data as Int

答:
This bug fix in the Jacoco (version0.8.8 Changelog) coverage tool offers an explanation:

Branch added by the Kotlin compiler version 1.6.0 and above for "unsafe" cast operator is filtered out during generation of report (GitHub 1266)

Thus, the Kotlin compiler may generate a hidden branch for the cast (checking whether the cast is possible at all) which then surfaces in the coverage tool used.

From a functional perspective, you may want to add a test case that covers the situation that result.data doesn’t contain an int. That would probably lead to full coverage of the cast statement as well.

Though I am not a Kotlin developer, the unsafe cast raises the following questions:

The null != errorCode check suggests that errorCode is of type Int? and not of type Int which can never be null.

This also suggests the type cast can be safe, via result.data as? Int, where the as? operator returns null on failure.

Interestingly the coverage of your null != errorCode if-condition suggests that both the true and false branch are covered. I doubt this is the case. Instead, the compiler may have concluded that the condition can never be false (since errorCode has the non nullable type Int), and therefore optimized the else branch away.

In other words, switching to Int? and as? will likely move the reported uncovered branch to your null != errorCode if-condition, where it makes more sense.


问:
Manim exception in text mobject example
I'm trying to run this example from Manim community documentation:

```<code>from manim import *

class HelloWorld(Scene):
    def construct(self):
        text = Text('Hello world').scale(3)
        self.add(text)
</code>```

For some reason I'm getting this error:

```<code>TypeError: __init__() got an unexpected keyword argument 'color'
</code>```

I'm using the latest version of Manim community (0.14.0)

What am I doing wrong?

The full output is:

(Python3.9) C:\Users\User\IdeaProjects\GraphConnectivityDemo>manim -pql scene.py HelloWorld
Manim Community v0.14.0
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\cli\render\commands.py:139 in render             │
│                                                                                │
│   136 │   │   for SceneClass in scene_classes_from_file(file):                                   │
│   137 │   │   │   try:                                                                           │
│   138 │   │   │   │   scene = SceneClass()                                                       │
│ ❱ 139 │   │   │   │   scene.render()                                                             │
│   140 │   │   │   except Exception:                                                              │
│   141 │   │   │   │   error_console.print_exception()                                            │
│   142 │   │   │   │   sys.exit(1)                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\scene\scene.py:219 in render                     │
│                                                                                │
│    216 │   │   """                                                                               │
│    217 │   │   self.setup()                                                                      │
│    218 │   │   try:                                                                              │
│ ❱  219 │   │   │   self.construct()                                                              │
│    220 │   │   except EndSceneEarlyException:                                                    │
│    221 │   │   │   pass                                                                          │
│    222 │   │   except RerunSceneException as e:                                                  │
│                                                                                │
│ C:\Users\User\IdeaProjects\GraphConnectivityDemo\scene.py:5 in construct                         │
│                                                                                │
│   2                                                                                │
│   3 class HelloWorld(Scene):                                                                     │
│   4 │   def construct(self):                                                                     │
│ ❱ 5 │   │   text = Text('Hello world').scale(3)                                                  │
│   6 │   │   self.add(text)                                                                       │
│   7                                                                                │
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\mobject\svg\text_mobject.py:472 in __init__      │
│                                                                                │
│    469 │   │   │   )                                                                             │
│    470 │   │   else:                                                                             │
│    471 │   │   │   self.line_spacing = self._font_size + self._font_size * self.line_spacing     │
│ ❱  472 │   │   file_name = self.text2svg()                                                       │
│    473 │   │   PangoUtils.remove_last_M(file_name)                                               │
│    474 │   │   super().__init__(                                                                 │
│    475 │   │   │   file_name,                                                                    │
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\mobject\svg\text_mobject.py:753 in text2svg      │
│                                                                                │
│    750 │   │   if os.path.exists(file_name):                                                     │
│    751 │   │   │   svg_file = file_name                                                          │
│    752 │   │   else:                                                                             │
│ ❱  753 │   │   │   settings = self.text2settings()                                               │
│    754 │   │   │   width = config["pixel_width"]                                                 │
│    755 │   │   │   height = config["pixel_height"]                                               │
│    756                                                                                │
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\mobject\svg\text_mobject.py:714 in text2settings │
│                                                                                │
│    711 │   │   │   │   temp_settings.append(TextSetting(start, setting.start, **setting_args))   │
│    712 │   │   │   start = setting.end                                                           │
│    713 │   │   if start != len(self.text):                                                       │
│ ❱  714 │   │   │   temp_settings.append(TextSetting(start, len(self.text), **setting_args))      │
│    715 │   │   settings = sorted(temp_settings, key=lambda setting: setting.start)               │
│    716 │   │                                                                                │
│    717 │   │   if re.search(r"\n", self.text):                                                   │
│                                                                                │
│ C:\Users\User\IdeaProjects\GraphConnectivityDemo\cmanimpango.pyx:9 in                            │
│ manimpango.cmanimpango.TextSetting.__init__                                                      │
│                                                                                │
│ [Errno 2] No such file or directory:                                                             │
│ 'C:\\Users\\User\\IdeaProjects\\GraphConnectivityDemo\\cmanimpango.pyx'                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
TypeError: __init__() got an unexpected keyword argument 'color'
```

答: You could try to upgrade manimpango via pip install -U manimpango.  As a workaround, using Tex instead would also work as long as you have LaTeX installed.

Title: Manim exception in text mobject example

Body:
I'm trying to run this example from Manim community documentation:

from manim import *

class HelloWorld(Scene):
    def construct(self):
        text = Text('Hello world').scale(3)
        self.add(text)

For some reason I'm getting this error:

TypeError: __init__() got an unexpected keyword argument 'color'

I'm using the latest version of Manim community (0.14.0)

What am I doing wrong?

The full output is:

(Python3.9) C:\Users\User\IdeaProjects\GraphConnectivityDemo>manim -pql scene.py HelloWorld
Manim Community v0.14.0
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\cli\render\commands.py:139 in render             │
│                                                                                │
│   136 │   │   for SceneClass in scene_classes_from_file(file):                                   │
│   137 │   │   │   try:                                                                           │
│   138 │   │   │   │   scene = SceneClass()                                                       │
│ ❱ 139 │   │   │   │   scene.render()                                                             │
│   140 │   │   │   except Exception:                                                              │
│   141 │   │   │   │   error_console.print_exception()                                            │
│   142 │   │   │   │   sys.exit(1)                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\scene\scene.py:219 in render                     │
│                                                                                │
│    216 │   │   """                                                                               │
│    217 │   │   self.setup()                                                                      │
│    218 │   │   try:                                                                              │
│ ❱  219 │   │   │   self.construct()                                                              │
│    220 │   │   except EndSceneEarlyException:                                                    │
│    221 │   │   │   pass                                                                          │
│    222 │   │   except RerunSceneException as e:                                                  │
│                                                                                │
│ C:\Users\User\IdeaProjects\GraphConnectivityDemo\scene.py:5 in construct                         │
│                                                                                │
│   2                                                                                │
│   3 class HelloWorld(Scene):                                                                     │
│   4 │   def construct(self):                                                                     │
│ ❱ 5 │   │   text = Text('Hello world').scale(3)                                                  │
│   6 │   │   self.add(text)                                                                       │
│   7                                                                                │
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\mobject\svg\text_mobject.py:472 in __init__      │
│                                                                                │
│    469 │   │   │   )                                                                             │
│    470 │   │   else:                                                                             │
│    471 │   │   │   self.line_spacing = self._font_size + self._font_size * self.line_spacing     │
│ ❱  472 │   │   file_name = self.text2svg()                                                       │
│    473 │   │   PangoUtils.remove_last_M(file_name)                                               │
│    474 │   │   super().__init__(                                                                 │
│    475 │   │   │   file_name,                                                                    │
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\mobject\svg\text_mobject.py:753 in text2svg      │
│                                                                                │
│    750 │   │   if os.path.exists(file_name):                                                     │
│    751 │   │   │   svg_file = file_name                                                          │
│    752 │   │   else:                                                                             │
│ ❱  753 │   │   │   settings = self.text2settings()                                               │
│    754 │   │   │   width = config["pixel_width"]                                                 │
│    755 │   │   │   height = config["pixel_height"]                                               │
│    756                                                                                │
│                                                                                │
│ C:\Users\User\Python3.9\lib\site-packages\manim\mobject\svg\text_mobject.py:714 in text2settings │
│                                                                                │
│    711 │   │   │   │   temp_settings.append(TextSetting(start, setting.start, **setting_args))   │
│    712 │   │   │   start = setting.end                                                           │
│    713 │   │   if start != len(self.text):                                                       │
│ ❱  714 │   │   │   temp_settings.append(TextSetting(start, len(self.text), **setting_args))      │
│    715 │   │   settings = sorted(temp_settings, key=lambda setting: setting.start)               │
│    716 │   │                                                                                │
│    717 │   │   if re.search(r"\n", self.text):                                                   │
│                                                                                │
│ C:\Users\User\IdeaProjects\GraphConnectivityDemo\cmanimpango.pyx:9 in                            │
│ manimpango.cmanimpango.TextSetting.__init__                                                      │
│                                                                                │
│ [Errno 2] No such file or directory:                                                             │
│ 'C:\\Users\\User\\IdeaProjects\\GraphConnectivityDemo\\cmanimpango.pyx'                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
TypeError: __init__() got an unexpected keyword argument 'color'


问:
Invoke a function on tool mode script reload
How do I invoke a function every time the Script is loaded or reloaded?</p>
```<code>tool

func _reload():
    print("Changes have been made and saved! Script has been reloaded")

func _load():
    print("Project was just opened! Script has been loaded")
</code>```

答:
I'm not sure what you mean by reloaded (or why it is an issue), but it probably is one of these:

When you add a Node to the scene tree (or when you enable a plugin, which is adding the EditorPlugin to scene tree of the editor), or when it is loaded (all plugins are loaded when you load the project), the code in _enter_tree will run. Similarly when it is removed (or when the plugin is disabled), the code in _exit_tree will run. Be aware that for tool scripts that you run manually (EditorScript), these don't work. So make a Node (or an EditorPlugin).

There is a signal that will notify when the script of an object changed. It is appropriately named "script_changed". So if you want to handle the situation when the tool script was modified, and thus reloaded, you could connect to that signal. You may also want to take advantage of the of _init, which is the first virtual method that Godot calls (on Nodes you can also use _enter_tree and _ready). The signal "script_changed" is emitted before _init is called in the new script.

If you want to handle when properties of a Node are modified (I'm including this since you mention "changed has been made"), you would have to use setters (with setget), or you could intercept the properties in _set.

Since you mention "Project was just opened", I think you want to make an EditorPlugin, and then you can use _enter_tree and _exit_tree.

I haven't found a way to get a notification when the currently edited scene on the editor is saved. However, saving the scene does not mean tool script are loaded or reloaded in anyway.

Body:
How do I invoke a function every time the Script is loaded or reloaded?

tool

func _reload():
    print("Changes have been made and saved! Script has been reloaded")

func _load():
    print("Project was just opened! Script has been loaded")


问:
Remove missing strings from an object after comparing previous state to new state
I am using react-multi-date-picker to create an exemptions scheduler. The react-multi-date-picker is used inside of a react-table as follows:

```<code>const [data, setData] = useState(0);
const [dateValues, setDateValues] = useState({});

const columns = useMemo(
  () => [
    {
      Header: "Exemptions",
      // First group columns
      columns: [
        {
          Header: "Exemptions",
          accessor: "exemptions",
          Cell: ({ row, data }) => (
            <DatePicker
              multiple
              key={data[row.index].id}
              onChange={(dateValues) => {
                const valueId = data[row.index].id;
                Object.keys(dateValues).map((key) => {
                  setDateValues((oldArray) => ({
                    ...oldArray,
                    [valueId]: {
                      ...oldArray[valueId],
                      [key]: dateValues[key]
                        ?.toDate?.()
                        .toISOString?.()
                        .substring?.(0, 10),
                    },
                  }));
                });
              }}
              plugins={[<DatePanel />]}
            />
          ),
        },
      ],
    },
  ],
  []
);
</code>```

data produces an object from an axios call with the following structure.

```<code>(1) [{…}]
0:
  exemptions: null
  id: 1
  name: "John Smith"
  user_supervisor: "Joe Black"
  [[Prototype]]: Object

</code>```

If I were to select 4 dates from the react-multi-date-picker and after my onChange call in the memoization hook, I am left with this in the dateValues:

```<code>{1: {…}}
1:
  0: "2022-02-02"
  1: "2022-02-03"
  2: "2022-02-08"
  3: "2022-02-08"
  [[Prototype]]: Object
[[Prototype]]: Object
</code>```

This all works as expected. What I am struggling with is removing dates from the dateValues object when a user deselects the date from the react-multi-date-picker. I have tried using a ternary, I have tried using .filter and .includes. Every option I have tried throws a different error.

I am at a mental block on the logic needed. My thoughts have been I need to compare the previous state with the new state and keep matching values while discarding any values that don't match between the two states. I just can't code it in a way that works. Any help on this would be much appreciated.

答:
if you were using filter on the dateValues the error was thrown most probably because you were trying to use that method on an object. you can use the filter method on arrays but not ob objects.
Try to convert dateValues to an array with Object.values(obj)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

and then chain the filter on it. Filter all the dates that are not equal to the deselected date and update the state with the result array coming from the filter method.

Body:
I am using react-multi-date-picker to create an exemptions scheduler. The react-multi-date-picker is used inside of a react-table as follows:

const [data, setData] = useState(0);
const [dateValues, setDateValues] = useState({});

const columns = useMemo(
  () => [
    {
      Header: "Exemptions",
      // First group columns
      columns: [
        {
          Header: "Exemptions",
          accessor: "exemptions",
          Cell: ({ row, data }) => (
            <DatePicker
              multiple
              key={data[row.index].id}
              onChange={(dateValues) => {
                const valueId = data[row.index].id;
                Object.keys(dateValues).map((key) => {
                  setDateValues((oldArray) => ({
                    ...oldArray,
                    [valueId]: {
                      ...oldArray[valueId],
                      [key]: dateValues[key]
                        ?.toDate?.()
                        .toISOString?.()
                        .substring?.(0, 10),
                    },
                  }));
                });
              }}
              plugins={[<DatePanel />]}
            />
          ),
        },
      ],
    },
  ],
  []
);

data produces an object from an axios call with the following structure.

(1) [{…}]
0:
  exemptions: null
  id: 1
  name: "John Smith"
  user_supervisor: "Joe Black"
  [[Prototype]]: Object

If I were to select 4 dates from the react-multi-date-picker and after my onChange call in the memoization hook, I am left with this in the dateValues:

{1: {…}}
1:
  0: "2022-02-02"
  1: "2022-02-03"
  2: "2022-02-08"
  3: "2022-02-08"
  [[Prototype]]: Object
[[Prototype]]: Object

This all works as expected. What I am struggling with is removing dates from the dateValues object when a user deselects the date from the react-multi-date-picker. I have tried using a ternary, I have tried using .filter and .includes. Every option I have tried throws a different error.

I am at a mental block on the logic needed. My thoughts have been I need to compare the previous state with the new state and keep matching values while discarding any values that don't match between the two states. I just can't code it in a way that works. Any help on this would be much appreciated.


问:
SQL Server 2008 Containstable generate negative rank with weighted_term
I have a table with full text search enabled on Title column. I try to make a weighted search with a containstable but i get an Arithmetic overflow for the Rank value. The query is as follow

```<code> SELECT ID, CAST(Res_Tbl.RANK AS Decimal) AS Relevancy , Title
  FROM table1 AS INNER JOIN
    CONTAINSTABLE(table1,Title,'ISABOUT("pétoncle" weight (.8), "pétoncle" weight (.8), "PÉTONCLE" weight (.8))',LANGUAGE 1036 ) AS Res_Tbl
     ON ID = Res_Tbl.[KEY]
</code>```

When I execute this query I get : Arithmetic overflow error for type int, value = -83886083125.000076.

If I remove one of the two ';' in the ISABOUT function the query complete successfully.

Note you need to have some results if there is no result the query complete successfully.

Does anybody know how to solve this ?

This question is also on dba.stackexchange.com

答:
Qualifier: Since I can't recreate this, I'm unable to know for sure if this will fix the problem.  However, these are some things that I'm seeing.

First off, the ampersand, pound sign, and semicolon are word-break characters.  That means, that instead of searching for the string "pétoncle", what you're actually searching for is "p", "233", and "toncle".  Clearly, that's not your intent.

I have to presume that you have the text "pétoncle" somewhere in your dataset.  That means you need that entire string to be complete.

There are a few things you can do.

1)  Turn off Stopwords all together.  You can do that by altering the full text index to turn it off.

Note that you have to have your database set to SQL Server 2008 compatability for this to not generate a syntax error:

```<code>ALTER FULLTEXT INDEX ON Table1 SET STOPLIST OFF;
</code>```

2) Create a new stoplist

If you create an empty StopList, you might be able to add the stopwords that you want or copy the system stoplist and remove the stopwords that you don't want.  (I would advise the second approach).

Having said that, I wasn't able to find the & or # in the system stoplist, so they may be hard coded.  You may have to simply turn the stoplist off.

3) Change your search to ignore the "pétoncle" case.

If you drop the "pétoncle" from the ISABOUT and change them to "p toncle", it might work:

```<code>'ISABOUT("pétoncle" weight (.8), "p toncle" weight (.8))'
</code>```

Those are just some ideas.  Like I said, without being able to access the system or recreate the scenario, we won't be able to help much.

Some more information for your researching pleasure:

Stopwords and Stoplists

Alter Fulltext Index syntax

FullText search using Thesaurus file and special characters

Body:
I have a table with full text search enabled on Title column. I try to make a weighted search with a containstable but i get an Arithmetic overflow for the Rank value. The query is as follow

 SELECT ID, CAST(Res_Tbl.RANK AS Decimal) AS Relevancy , Title
  FROM table1 AS INNER JOIN
    CONTAINSTABLE(table1,Title,'ISABOUT("pétoncle" weight (.8), "pétoncle" weight (.8), "PÉTONCLE" weight (.8))',LANGUAGE 1036 ) AS Res_Tbl
     ON ID = Res_Tbl.[KEY]

When I execute this query I get : Arithmetic overflow error for type int, value = -83886083125.000076.

If I remove one of the two ';' in the ISABOUT function the query complete successfully.

Note you need to have some results if there is no result the query complete successfully.

Does anybody know how to solve this ?

This question is also on dba.stackexchange.com

Body:
Qualifier: Since I can't recreate this, I'm unable to know for sure if this will fix the problem.  However, these are some things that I'm seeing.

First off, the ampersand, pound sign, and semicolon are word-break characters.  That means, that instead of searching for the string "p&#233;toncle", what you're actually searching for is "p", "233", and "toncle".  Clearly, that's not your intent.

I have to presume that you have the text "p&#233;toncle" somewhere in your dataset.  That means you need that entire string to be complete.

There are a few things you can do.

1)  Turn off Stopwords all together.  You can do that by altering the full text index to turn it off.

Note that you have to have your database set to SQL Server 2008 compatability for this to not generate a syntax error:

ALTER FULLTEXT INDEX ON Table1 SET STOPLIST OFF;

2) Create a new stoplist

If you create an empty StopList, you might be able to add the stopwords that you want or copy the system stoplist and remove the stopwords that you don't want.  (I would advise the second approach).

Having said that, I wasn't able to find the & or # in the system stoplist, so they may be hard coded.  You may have to simply turn the stoplist off.

3) Change your search to ignore the "p&#233;toncle" case.

If you drop the "p&#233;toncle" from the ISABOUT and change them to "p toncle", it might work:

'ISABOUT("pétoncle" weight (.8), "p toncle" weight (.8))'

Those are just some ideas.  Like I said, without being able to access the system or recreate the scenario, we won't be able to help much.

Some more information for your researching pleasure:

Stopwords and Stoplists

Alter Fulltext Index syntax

FullText search using Thesaurus file and special characters


问:
How to do I proper Error-Handling for a File-Reader in Rust
I would like to load a Json file to a Vec.

When I do everything with unwrap() it works fine. Now I want to Catch some Errors like "File not Found" and Handle them, but I'm not able to figure out how to do it probably.

Maybe you could help me? Thanks in advance.

```<code>fn read_from_file(filename: &str) -> Result<Vec<Card>, io::Error> {
    let f = File::open(filename);
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };
    let mut s = String::new();
    f.read_to_string(&mut s)?;

    let data = serde_json::from_str(&s)?;
    Ok(data)
}

fn main() {
    let mut cards = read_from_file("Test.json");
    let mut cards = match cards {
        Ok(Vec) => Vec,
        Err(_) => {
            println!(
                "File was not found!\n
            Do you want to create a new one? (y/N)"
            );
            let mut answer = String::new();
            io::stdin()
                .read_line(&mut answer)
                .expect("Failed to read line");
            answer.pop();
            if answer == "y" {
                let mut cards: Vec<Card> = Vec::new();
                return cards;
            } else {
                panic!("No file was found and you did not allow to create a new one");
            }
        }
    };
}
</code>```

答:
You need to check what the ErrorKind value is. If it is NotFound, then you know the file doesn't exist.

In your code:

```<code>let f = File::open(filename);
let mut f = match f {
    Ok(file) => file,
    Err(e) => return Err(e),
};
</code>```

, where you have Err(e) match arm, the type of e is std::io::Error. That struct has a method kind() which is what you need to check. Like this:

```<code>let mut f = match f {
    Ok(file) => file,
    Err(e) => {
        if e.kind() == ErrorKind::NotFound {
            println!("Oh dear, the file doesn't exist!");
        }
        ...
    }
};
</code>```

Body:
I would like to load a Json file to a Vec.

When I do everything with unwrap() it works fine. Now I want to Catch some Errors like "File not Found" and Handle them, but I'm not able to figure out how to do it probably.

Maybe you could help me? Thanks in advance.

fn read_from_file(filename: &str) -> Result<Vec<Card>, io::Error> {
    let f = File::open(filename);
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };
    let mut s = String::new();
    f.read_to_string(&mut s)?;

    let data = serde_json::from_str(&s)?;
    Ok(data)
}

fn main() {
    let mut cards = read_from_file("Test.json");
    let mut cards = match cards {
        Ok(Vec) => Vec,
        Err(_) => {
            println!(
                "File was not found!\n
            Do you want to create a new one? (y/N)"
            );
            let mut answer = String::new();
            io::stdin()
                .read_line(&mut answer)
                .expect("Failed to read line");
            answer.pop();
            if answer == "y" {
                let mut cards: Vec<Card> = Vec::new();
                return cards;
            } else {
                panic!("No file was found and you did not allow to create a new one");
            }
        }
    };
}

Body:
You need to check what the ErrorKind value is. If it is NotFound, then you know the file doesn't exist.

In your code:

let f = File::open(filename);
let mut f = match f {
    Ok(file) => file,
    Err(e) => return Err(e),
};

, where you have Err(e) match arm, the type of e is std::io::Error. That struct has a method kind() which is what you need to check. Like this:

let mut f = match f {
    Ok(file) => file,
    Err(e) => {
        if e.kind() == ErrorKind::NotFound {
            println!("Oh dear, the file doesn't exist!");
        }
        ...
    }
};


问:
How to restrict user from selecting past time in Flutter
For example if it's 16:00 then selecting 15:59 or some earlier time from the same day shouldn't be allowed.</p>

答:
You should check in the options of whichever component you are using.

For instance for flutter_datetime_picker package, there is a property minTime that you could set at the current date time to prevent selecting a past time.

```<code>TextButton(
    onPressed: () {
        DatePicker.showDatePicker(
           context,
           minTime: DateTime.now(),
           maxTime: DateTime(2030, 12, 31),
           onChanged: (date) {
               print('change $date');
           },
           currentTime: DateTime.now(),
        );
    },
    child: Text(
        'Show Time Picker',
    ),
);
</code>```

Body:
You should check in the options of whichever component you are using.

For instance for flutter_datetime_picker package, there is a property minTime that you could set at the current date time to prevent selecting a past time.

TextButton(
    onPressed: () {
        DatePicker.showDatePicker(
           context,
           minTime: DateTime.now(),
           maxTime: DateTime(2030, 12, 31),
           onChanged: (date) {
               print('change $date');
           },
           currentTime: DateTime.now(),
        );
    },
    child: Text(
        'Show Time Picker',
    ),
);


问:
Kotlin: try catch in CoroutineScope still crash the app
I'm using the code below for a network request throught okhttp3:

runOnDefaultDispatcher {
                try {
                    val newsResponse = Xxxx.xxxxClient.getNews()
                    if (newsResponse.success && newsResponse.data != null && newsResponse.data.count() > 0) {
                        runOnMainDispatcher {
                            val adapter = NewsAdapter(newsResponse.data, getString(R.string.news)).also {
                                initListener(it, newsResponse.data)
                            }
                            binding.list.adapter = adapter
                            adapter.notifyDataSetChanged()
                        }
                    }
                } catch (exception: Exception) {
                    runOnMainDispatcher {
                        binding.list.visibility = View.GONE

                        val errorLayout = view.findViewById<RelativeLayout>(R.id.error_layout)
                        errorLayout.visibility = View.VISIBLE
                        errorLayout.findViewById<TextView>(R.id.error_title).text = "Oops..."
                        errorLayout.findViewById<TextView>(R.id.error_message).text = exception.message
                    }
                }
            }
```
<p>The implementation code of <code>runOnDefaultDispatcher</code> and <code>runOnMainDispatcher</code> is down below:</p>
<pre class="lang-kotlin prettyprint-override"><code>import kotlinx.coroutines.*

fun block(block: suspend CoroutineScope.() -> Unit): suspend CoroutineScope.() -> Unit {
    return block
}

fun runOnDefaultDispatcher(block: suspend CoroutineScope.() -> Unit) =
    GlobalScope.launch(Dispatchers.Default, block = block)

suspend fun <T> onDefaultDispatcher(block: suspend CoroutineScope.() -> T) =
    withContext(Dispatchers.Default, block = block)

fun runOnIoDispatcher(block: suspend CoroutineScope.() -> Unit) =
    GlobalScope.launch(Dispatchers.IO, block = block)

suspend fun <T> onIoDispatcher(block: suspend CoroutineScope.() -> T) =
    withContext(Dispatchers.IO, block = block)

fun runOnMainDispatcher(block: suspend CoroutineScope.() -> Unit) =
    GlobalScope.launch(Dispatchers.Main.immediate, block = block)

suspend fun <T> onMainDispatcher(block: suspend CoroutineScope.() -> T) =
    withContext(Dispatchers.Main.immediate, block = block)

</code>```

I except the exception would be caught and no crash would appear.

However the application still CRASH:

```<code>FATAL EXCEPTION: DefaultDispatcher-worker-2
Java.net.SocketException: Connection reset
</code>```

答:
The calls to launch don't work well with try/catch.

e.g. this will crash the app

```<code>try {
    GlobalScope.launch { throw Excepton() }
} catch (e: Exception) {
}
</code>```

On the other hand, suspend functions work with try/catch as you would expect so this example DOES NOT crash the app:

```<code>suspend fun bang(): Unit = throw Exception()

try {
    bang()
} catch (e: Exception) {
}
</code>```

In your code you have launch inside try/catch, meaning you have a scenario like the first example here.

The solution is to build your program as suspend functions, and only use launch one to execute the result (note: this doesn't apply universally but does apply in this scenario).

When running the program you probably want to use lifecycleScope.

Also you might want to consider using a ViewModel so that the network call survives configuration changes.

You can check the Kotlin Coroutines on Android guide for more.

Body:
I'm using the code below for a network request throught okhttp3:

runOnDefaultDispatcher {
                try {
                    val newsResponse = Xxxx.xxxxClient.getNews()
                    if (newsResponse.success && newsResponse.data != null && newsResponse.data.count() > 0) {
                        runOnMainDispatcher {
                            val adapter = NewsAdapter(newsResponse.data, getString(R.string.news)).also {
                                initListener(it, newsResponse.data)
                            }
                            binding.list.adapter = adapter
                            adapter.notifyDataSetChanged()
                        }
                    }
                } catch (exception: Exception) {
                    runOnMainDispatcher {
                        binding.list.visibility = View.GONE

                        val errorLayout = view.findViewById<RelativeLayout>(R.id.error_layout)
                        errorLayout.visibility = View.VISIBLE
                        errorLayout.findViewById<TextView>(R.id.error_title).text = "Oops..."
                        errorLayout.findViewById<TextView>(R.id.error_message).text = exception.message
                    }
                }
            }

The implementation code of runOnDefaultDispatcher and runOnMainDispatcher is down below:

import kotlinx.coroutines.*

fun block(block: suspend CoroutineScope.() -> Unit): suspend CoroutineScope.() -> Unit {
    return block
}

fun runOnDefaultDispatcher(block: suspend CoroutineScope.() -> Unit) =
    GlobalScope.launch(Dispatchers.Default, block = block)

suspend fun <T> onDefaultDispatcher(block: suspend CoroutineScope.() -> T) =
    withContext(Dispatchers.Default, block = block)

fun runOnIoDispatcher(block: suspend CoroutineScope.() -> Unit) =
    GlobalScope.launch(Dispatchers.IO, block = block)

suspend fun <T> onIoDispatcher(block: suspend CoroutineScope.() -> T) =
    withContext(Dispatchers.IO, block = block)

fun runOnMainDispatcher(block: suspend CoroutineScope.() -> Unit) =
    GlobalScope.launch(Dispatchers.Main.immediate, block = block)

suspend fun <T> onMainDispatcher(block: suspend CoroutineScope.() -> T) =
    withContext(Dispatchers.Main.immediate, block = block)

I except the exception would be caught and no crash would appear.

However the application still CRASH:

FATAL EXCEPTION: DefaultDispatcher-worker-2
Java.net.SocketException: Connection reset

Body:
The calls to launch don't work well with try/catch.

e.g. this will crash the app

try {
    GlobalScope.launch { throw Excepton() }
} catch (e: Exception) {
}

On the other hand, suspend functions work with try/catch as you would expect so this example DOES NOT crash the app:

suspend fun bang(): Unit = throw Exception()

try {
    bang()
} catch (e: Exception) {
}

In your code you have launch inside try/catch, meaning you have a scenario like the first example here.

The solution is to build your program as suspend functions, and only use launch one to execute the result (note: this doesn't apply universally but does apply in this scenario).

When running the program you probably want to use lifecycleScope.

Also you might want to consider using a ViewModel so that the network call survives configuration changes.

You can check the Kotlin Coroutines on Android guide for more.


问:
I had made a small dictionary, where i am asking user to find anything from the the dictionary. i want user to input string and numeric value
```<code>a = {"green":"hot","Rebukes":"reprimand",19: "my birthday"}
b=input("Enter the word of your choice")
print(a[b])
</code>```

Error happens when I as a user give 19 as input to the program.
I know that input function by default takes string value and I want user to access any key from the dictionary whether it is a string or integer or float.

答:
You read your input as a string so when you enter 19 your dictionary will look for the string key '19' instead of the integer 19.
You could test if the input is a number and if it is, cast the string to an integer:

```<code>a = {"green":"hot", "Rebukes":"reprimand", 19: "my birthday"}
b = input("Enter the word of your choice")
if b.isnumeric():
    b = int(b)
print(a[b])
</code>```

However, it might be a good idea to have the dictionary keys all of the same type.

Body:
a = {"green":"hot","Rebukes":"reprimand",19: "my birthday"}
b=input("Enter the word of your choice")
print(a[b])

Error happens when I as a user give 19 as input to the program.
I know that input function by default takes string value and I want user to access any key from the dictionary whether it is a string or integer or float.

Body:
You read your input as a string so when you enter 19 your dictionary will look for the string key '19' instead of the integer 19.
You could test if the input is a number and if it is, cast the string to an integer:

a = {"green":"hot", "Rebukes":"reprimand", 19: "my birthday"}
b = input("Enter the word of your choice")
if b.isnumeric():
    b = int(b)
print(a[b])

However, it might be a good idea to have the dictionary keys all of the same type.


问:
How to bound the draggable div within the container
I am using react with typescript and I implemented the w3school drag div example in my react app. Now, I am trying to bound this draggable div within the boundary. Currently, my box is moving outside the container. please help how to achieve this without using any third-party library.

Here is my sandbox demo

my code:

```<code>import "./styles.css";
import React, { useRef } from "react";

export default function App() {
  const dragRef = useRef<HTMLDivElement>(null);
  let pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;

  const drag = (event: any) => {
    const boundingBox = dragRef.current;

    if (boundingBox) {
      event = event || window.event;
      event.preventDefault();
      pos1 = pos3 - event.clientX;
      pos2 = pos4 - event.clientY;
      pos3 = event.clientX;
      pos4 = event.clientY;
      boundingBox.style.top = boundingBox.offsetTop - pos2 + "px";
      boundingBox.style.left = boundingBox.offsetLeft - pos1 + "px";
    }
  };

  const stop = () => {
    const boundingBox = dragRef.current;
    if (boundingBox) {
      boundingBox.onmouseup = null;
      boundingBox.onmousemove = null;
    }
  };

  const start = (event: any) => {
    const box = dragRef.current;
    if (box) {
      event = event || window.event;
      event.preventDefault();
      pos3 = event.clientX;
      pos4 = event.clientY;
      box.onmouseup = stop;
      box.onmousemove = drag;
    }
  };

  return (
    <div className="App">
      <div
        ref={dragRef}
        className="draggableDiv"
        onMouseDown={start}
        onMouseMove={drag}
        onMouseUp={stop}
      ></div>
    </div>
  );
}
</code>```

and the external CSS file:

```<code>.App {
  font-family: sans-serif;
  height: 350px;
  width: 400px;
  background-color: rgb(132, 190, 241);
  position: relative;
}

.draggableDiv {
  position: absolute;
  height: 40px;
  width: 40px;
  background-color: red;
  cursor: grab;
}
</code>```

答:
You can keep another ref to the draggable area and check if the clientX and clientY are within that range.

Create another ref and attach to draggable area div.

```<code>const dragAreaRef = useRef<HTMLDivElement>(null);
...
...
  return (
    <div className="App" ref={dragAreaRef}>
      ...
    </div>
  );
</code>```

Update the drag function like below.

```<code>  const drag = (event: any) => {
    const boundingBox = dragRef.current;

    const {
      left,
      right,
      top,
      bottom
    } = dragAreaRef.current?.getBoundingClientRect();

    if (boundingBox) {
      event = event || window.event;
      if (
        event.clientX > left &&
        event.clientX < right &&
        event.clientY > top &&
        event.clientY < bottom
      ) {
        event.preventDefault();
        pos1 = pos3 - event.clientX;
        pos2 = pos4 - event.clientY;
        pos3 = event.clientX;
        pos4 = event.clientY;
        boundingBox.style.top = boundingBox.offsetTop - pos2 + "px";
        boundingBox.style.left = boundingBox.offsetLeft - pos1 + "px";
      }
    }
  };
</code>```

Body:
I am using react with typescript and I implemented the w3school drag div example in my react app. Now, I am trying to bound this draggable div within the boundary. Currently, my box is moving outside the container. please help how to achieve this without using any third-party library.

Here is my sandbox demo

my code:

import "./styles.css";
import React, { useRef } from "react";

export default function App() {
  const dragRef = useRef<HTMLDivElement>(null);
  let pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;

  const drag = (event: any) => {
    const boundingBox = dragRef.current;

    if (boundingBox) {
      event = event || window.event;
      event.preventDefault();
      pos1 = pos3 - event.clientX;
      pos2 = pos4 - event.clientY;
      pos3 = event.clientX;
      pos4 = event.clientY;
      boundingBox.style.top = boundingBox.offsetTop - pos2 + "px";
      boundingBox.style.left = boundingBox.offsetLeft - pos1 + "px";
    }
  };

  const stop = () => {
    const boundingBox = dragRef.current;
    if (boundingBox) {
      boundingBox.onmouseup = null;
      boundingBox.onmousemove = null;
    }
  };

  const start = (event: any) => {
    const box = dragRef.current;
    if (box) {
      event = event || window.event;
      event.preventDefault();
      pos3 = event.clientX;
      pos4 = event.clientY;
      box.onmouseup = stop;
      box.onmousemove = drag;
    }
  };

  return (

  );
}

and the external CSS file:

.App {
  font-family: sans-serif;
  height: 350px;
  width: 400px;
  background-color: rgb(132, 190, 241);
  position: relative;
}

.draggableDiv {
  position: absolute;
  height: 40px;
  width: 40px;
  background-color: red;
  cursor: grab;
}

Body:
You can keep another ref to the draggable area and check if the clientX and clientY are within that range.

Create another ref and attach to draggable area div.

const dragAreaRef = useRef<HTMLDivElement>(null);
...
...
  return (
    <div className="App" ref={dragAreaRef}>
      ...
    </div>
  );

Update the drag function like below.

  const drag = (event: any) => {
    const boundingBox = dragRef.current;

    const {
      left,
      right,
      top,
      bottom
    } = dragAreaRef.current?.getBoundingClientRect();

    if (boundingBox) {
      event = event || window.event;
      if (
        event.clientX > left &&
        event.clientX < right &&
        event.clientY > top &&
        event.clientY < bottom
      ) {
        event.preventDefault();
        pos1 = pos3 - event.clientX;
        pos2 = pos4 - event.clientY;
        pos3 = event.clientX;
        pos4 = event.clientY;
        boundingBox.style.top = boundingBox.offsetTop - pos2 + "px";
        boundingBox.style.left = boundingBox.offsetLeft - pos1 + "px";
      }
    }
  };


问:
How does a Gmail message Id or ThreadId map to the new Gmail UI?
Edit: addressing the first comment below and for clarity, this isn't a code question. The question is simply:

What do I put into the URI querystring of the new Gmail UI to view a draft message created by the Gmail API?

Despite this not really being a code question, I'm asking on Stack Overflow as it's Google's preferred platform for Gmail API questions.

--

If I view a draft message in the new Gmail UI, the URI is something like this:

https://mail.google.com/mail/u/1/?zx=iij9apqgzdf4#drafts?compose=jrjtXSqXwlFGnSGCQgDCdnHGVFdlpFMgzsCNgpQstQLxdLCMkjKstBmWZkCmjhWTQnpsZCJF

I can't see any way to create such a link from the Id or ThreadId of a message created via the Gmail API.

Previously, one could do this:

https://mail.google.com/mail/u/1/?zx=ov61dxfbrcga#drafts?compose=1631caae9dbb074d

where the value of "compose" is the Id.

How can the same thing be accomplished in the new UI?

答:
I was struggling because I wanted it to work with multiple accounts. However the authuser parameter did not help.

Inserting the email address instead of the integer after the u/ component solved the problem.

```<code>https://mail.google.com/mail/u/{email_address}/#drafts?compose={message_id}
</code>```

The message id is the one provided by the API.

Body:
I was struggling because I wanted it to work with multiple accounts. However the authuser parameter did not help.

Inserting the email address instead of the integer after the u/ component solved the problem.

https://mail.google.com/mail/u/{email_address}/#drafts?compose={message_id}

The message id is the one provided by the API.