问:
Couldn't install mysql2 0.5.3 in M1 MacBook Big Sur
Hi I am trying to install mysql2 gem in MacBook M1 Big Sur, I am getting the the following errors.

```<code>ld: library not found for -lzstd
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1
</code>```

Full Error

```<code>Using mysql_config at /opt/homebrew/bin/mysql_config
-----
checking for mysql.h... yes
checking for errmsg.h... yes
checking for SSL_MODE_DISABLED in mysql.h... yes
checking for SSL_MODE_PREFERRED in mysql.h... yes
checking for SSL_MODE_REQUIRED in mysql.h... yes
checking for SSL_MODE_VERIFY_CA in mysql.h... yes
checking for SSL_MODE_VERIFY_IDENTITY in mysql.h... yes
checking for MYSQL.net.vio in mysql.h... yes
checking for MYSQL.net.pvio in mysql.h... no
checking for MYSQL_ENABLE_CLEARTEXT_PLUGIN in mysql.h... yes
checking for SERVER_QUERY_NO_GOOD_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_NO_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_WAS_SLOW in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_ON in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_OFF in mysql.h... yes
checking for my_bool in mysql.h... no
-----
Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load
-----
-----
Setting libpath to /opt/homebrew/Cellar/mysql/8.0.26/lib
-----
creating Makefile

current directory: /Users/santosh/.rvm/gems/ruby-2.6.3/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR=" clean

current directory: /Users/santosh/.rvm/gems/ruby-2.6.3/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR="
compiling client.c
compiling infile.c
compiling mysql2_ext.c
compiling result.c
compiling statement.c
linking shared-object mysql2/mysql2.bundle
ld: library not found for -lzstd
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/santosh/.rvm/gems/ruby-2.6.3/gems/mysql2-0.5.3 for inspection.
Results logged to /Users/santosh/.rvm/gems/ruby-2.6.3/extensions/-darwin-20/2.6.0/mysql2-0.5.3/gem_make.out

An error occurred while installing mysql2 (0.5.3), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.3' --source 'https://rubygems.org/'` succeeds before bundling.
</code>```

I tried to install with different version of Ruby, nothing went well.

答:
Apple Macbook air M1. Monterey. You need to install MySQL and openssl using brew .

This works for me.

```<code>gem install mysql2 -- --with-opt-dir=/opt/homebrew/opt/openssl@3 --with-mysql-dir=/opt/homebrew/opt/mysql
</code>```

Body:
Hi I am trying to install mysql2 gem in MacBook M1 Big Sur, I am getting the the following errors.

ld: library not found for -lzstd
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1

Full Error

Using mysql_config at /opt/homebrew/bin/mysql_config
-----
checking for mysql.h... yes
checking for errmsg.h... yes
checking for SSL_MODE_DISABLED in mysql.h... yes
checking for SSL_MODE_PREFERRED in mysql.h... yes
checking for SSL_MODE_REQUIRED in mysql.h... yes
checking for SSL_MODE_VERIFY_CA in mysql.h... yes
checking for SSL_MODE_VERIFY_IDENTITY in mysql.h... yes
checking for MYSQL.net.vio in mysql.h... yes
checking for MYSQL.net.pvio in mysql.h... no
checking for MYSQL_ENABLE_CLEARTEXT_PLUGIN in mysql.h... yes
checking for SERVER_QUERY_NO_GOOD_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_NO_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_WAS_SLOW in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_ON in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_OFF in mysql.h... yes
checking for my_bool in mysql.h... no
-----
Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load
-----
-----
Setting libpath to /opt/homebrew/Cellar/mysql/8.0.26/lib
-----
creating Makefile

current directory: /Users/santosh/.rvm/gems/ruby-2.6.3/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR=" clean

current directory: /Users/santosh/.rvm/gems/ruby-2.6.3/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR="
compiling client.c
compiling infile.c
compiling mysql2_ext.c
compiling result.c
compiling statement.c
linking shared-object mysql2/mysql2.bundle
ld: library not found for -lzstd
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/santosh/.rvm/gems/ruby-2.6.3/gems/mysql2-0.5.3 for inspection.
Results logged to /Users/santosh/.rvm/gems/ruby-2.6.3/extensions/-darwin-20/2.6.0/mysql2-0.5.3/gem_make.out

An error occurred while installing mysql2 (0.5.3), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.3' --source 'https://rubygems.org/'` succeeds before bundling.

I tried to install with different version of Ruby, nothing went well.

Body:
Apple Macbook air M1. Monterey. You need to install MySQL and openssl using brew .

This works for me.

gem install mysql2 -- --with-opt-dir=/opt/homebrew/opt/openssl@3 --with-mysql-dir=/opt/homebrew/opt/mysql


来源: stackexchange

问:
Can't position button element

I created a submit button using bootstrap but I want to place it where the arrow pointing but I no matter what I write the position doesn't change it's like the button stick to the position and I can't reposition it
how can I place it to be there?

.container {
  position: absolute;
  top: 30%;
  left: 30%;
  transform: translate(-50%, -50%);
  text-align: center;
  /*give the text bolder font*/
  font-weight: bold;
}
/*set the input under the span element*/
input[type=text] {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  padding: 12px 10px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  /*set the space from left to 30%*/
  margin-left: 30%;
}
/* set the button under the input element*/
button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  /*set the space from left to 30%*/
  margin-left: 30%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>quiz</title>
    <link rel="stylesheet" href="quiz2.css">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

</head>
<body>
  <div class="container">
    <span id="question">What type of file do you need to open javascript file ?</span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
  </div></code>```

答:
I just define a button-container class and use flex & justify:

.container {
  position: absolute;
  top: 30%;
  left: 30%;
  transform: translate(-50%, -50%);
  text-align: center;
  /*give the text bolder font*/
  font-weight: bold;
}

/*set the input under the span element*/

input[type=text] {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  padding: 12px 10px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  /*set the space from left to 30%*/
  margin-left: 30%;
}

/* set the button under the input element*/

button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  /*set the space from left to 30%*/
  margin-left: 30%;
}

.button-container {
  display: flex;
  justify-content: start;
  margin-left: 30%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>quiz</title>
  <link rel="stylesheet" href="quiz2.css">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

</head>

<body>
  <div class="container">
    <span id="question">What type of file do you need to open javascript file ?</span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <div class="button-container">
      <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
    </div>
  </div></code>```

ContentLicense: CC BY-SA 4.0

Title: Can't position button element

Body:
I created a submit button using bootstrap but I want to place it where the arrow pointing but I no matter what I write the position doesn't change it's like the button stick to the position and I can't reposition it
how can I place it to be there?

.container {
  position: absolute;
  top: 30%;
  left: 30%;
  transform: translate(-50%, -50%);
  text-align: center;
  /*give the text bolder font*/
  font-weight: bold;
}
/*set the input under the span element*/
input[type=text] {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  padding: 12px 10px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  /*set the space from left to 30%*/
  margin-left: 30%;
}
/* set the button under the input element*/
button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  /*set the space from left to 30%*/
  margin-left: 30%;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>quiz</title>
    <link rel="stylesheet" href="quiz2.css">

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

    What type of file do you need to open javascript file ?

      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">

    <button type="button" id="submit" class="btn btn-outline-success">Submit</button>

Body:
I just define a button-container class and use flex & justify:

.container {
  position: absolute;
  top: 30%;
  left: 30%;
  transform: translate(-50%, -50%);
  text-align: center;
  /*give the text bolder font*/
  font-weight: bold;
}

/*set the input under the span element*/

input[type=text] {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  padding: 12px 10px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  /*set the space from left to 30%*/
  margin-left: 30%;
}

/* set the button under the input element*/

button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  /*set the space from left to 30%*/
  margin-left: 30%;
}

.button-container {
  display: flex;
  justify-content: start;
  margin-left: 30%;
}

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>quiz</title>
  <link rel="stylesheet" href="quiz2.css">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

</head>

<body>
  <div class="container">
    <span id="question">What type of file do you need to open javascript file ?</span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <div class="button-container">
      <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
    </div>
  </div>


答:
If you're able to change the HTML, here's a way:

Wrap your button inside another div:

   <button type="button" id="submit" class="btn btn-outline-success">Submit</button>

```
<p>Then set the <code>margin-left</code> on that wrapper:</p>
<pre class="lang-css prettyprint-override"><code>.button-wrapper {
  /*set the space from left to 30%*/
  margin-left: 30%;
}
</code>```

Check this snippet for the result.

.container {
  position: absolute;
  top: 30%;
  left: 30%;
  transform: translate(-50%, -50%);
  /*give the text bolder font*/
  font-weight: bold;
}

/*set the input under the span element*/

input[type=text] {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  padding: 12px 10px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  /*set the space from left to 30%*/
  margin-left: 30%;
}

/* set the button under the input element*/

button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button-wrapper {
  /*set the space from left to 30%*/
  margin-left: 30%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>quiz</title>
  <link rel="stylesheet" href="quiz2.css">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

</head>

<body>
  <div class="container">
    <span id="question"></span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <div class="button-wrapper">
      <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
    </div>
  </div></code>```

Title: Can't position button element

Body:
If you're able to change the HTML, here's a way:

Wrap your button inside another div:

<div class="button-wrapper">
   <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
</div>

Then set the margin-left on that wrapper:

.button-wrapper {
  /*set the space from left to 30%*/
  margin-left: 30%;
}

Check this snippet for the result.

.container {
  position: absolute;
  top: 30%;
  left: 30%;
  transform: translate(-50%, -50%);
  /*give the text bolder font*/
  font-weight: bold;
}

/*set the input under the span element*/

input[type=text] {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
  padding: 12px 10px;
  width: 100%;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  /*set the space from left to 30%*/
  margin-left: 30%;
}

/* set the button under the input element*/

button {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button-wrapper {
  /*set the space from left to 30%*/
  margin-left: 30%;
}

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>quiz</title>
  <link rel="stylesheet" href="quiz2.css">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

</head>

<body>
  <div class="container">
    <span id="question"></span>
    <div class="input-group flex-nowrap">
      <input type="text" id="answer" class="form-control" placeholder="Answer Here..." aria-label="Username" aria-describedby="addon-wrapping">
    </div>
    <div class="button-wrapper">
      <button type="button" id="submit" class="btn btn-outline-success">Submit</button>
    </div>
  </div>


问:
How to add quotes from specific delimiter to end of the line, using awk?
I am trying to modify a file: (file.txt)

```<code>abc~123~xyz~123456~12~0.12~14~1.1~
omn~124~xdz~923231~13~0.0~13~1.1~14~0.45~19~80.1~
</code>```

to (new_file.txt)

```<code>abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"
</code>```

I tried using awk command:

```<code>awk -F'~' '{for(i=1;i<=4;i++){printf "%s~", $i}; printf"\""} {for(i=5;i<=NF;i+=1){printf "%s~", $i}; printf "\"\n"}' file.txt > new_file.txt
</code>```

but I am getting output as:

```<code>abc~123~xyz~123456~"12~0.12~14~1.1~~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~~"
</code>```

Can anyone help me out in this as I am getting an extra "~" at end of each line? Any reference would also be helpful as I get confused while dealing with sed and awk commands.

Body:
I am trying to modify a file: (file.txt)

abc~123~xyz~123456~12~0.12~14~1.1~
omn~124~xdz~923231~13~0.0~13~1.1~14~0.45~19~80.1~

to (new_file.txt)

abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"

I tried using awk command:

awk -F'~' '{for(i=1;i<=4;i++){printf "%s~", $i}; printf"\""} {for(i=5;i<=NF;i+=1){printf "%s~", $i}; printf "\"\n"}' file.txt > new_file.txt

but I am getting output as:

abc~123~xyz~123456~"12~0.12~14~1.1~~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~~"

Can anyone help me out in this as I am getting an extra "~" at end of each line? Any reference would also be helpful as I get confused while dealing with sed and awk commands.

Body:
This sed will fairly simple solution for this:

sed -E 's/^(([^~]*~){4})(.*)/\1"\3"/' file

abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"

Similarly using gnu awk:

awk '{print gensub(/^(([^~]*~){4})(.*)/, "\\1\"\\3\"", "1")}' file

abc~123~xyz~123456~"12~0.12~14~1.1~"
omn~124~xdz~923231~"13~0.0~13~1.1~14~0.45~19~80.1~"


问:
How to enlarge Material-ui Rating icons
I am using npm to show develop a widget.
I want to use material-ui Ratin component and I have integrate it. But when I place the widget in a webpage, it has a html font-size: 62.5%, so the component is too small because in the icon style, there are a 1em unit in height and in width.
screenshot.

This is my code:

import React from 'react';
import Rating from '@material-ui/lab/Rating';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import { withStyles } from '@material-ui/core/styles';
import StarOutlineIcon from '@material-ui/icons/StarOutline';

const styles = theme => ({
  iconFilled:{
    color:theme.palette.primary.main,
  },
  iconEmpty:{
    color:theme.palette.primary.main
  }
})

class SimpleRating extends React.Component{

  state = {
    disabled: false,
    rating: 0,
    opinion: "",
  };

  changeRating(event, newRating) {
    this.setState({
      rating: newRating,
      disabled: true
    });

    this.props.send_rating(newRating)
  }

  defaultLabelText(value) {
    let text="sin calificación"
    if (value===1){
      text = "una estrella"
    }
    else if (value>1 && value<=5) {
      text = ""+ value + " estrellas"
    }
    return(text)
  }

  render() {
  const { classes } = this.props;
  return (

      <Box component="fieldset" mb={3} borderColor="transparent">
        <Typography component="legend"></Typography>
        <Rating
          classes={{
            iconFilled: classes.iconFilled,
            iconEmpty: classes.iconEmpty
          }}
          emptyIcon = {<StarOutlineIcon></StarOutlineIcon>}
          name={"rating_"+this.props.number}
          disabled={this.state.disabled}
          getLabelText={this.defaultLabelText.bind(this)}
          onChange={this.changeRating.bind(this)}
          value={this.state.rating}
        />
      </Box>

  );
    }
}

export default withStyles(styles)(SimpleRating);```

Althougth I have been able to change the color with the styles, I cannot modify that down.
How can I change that properties of the icon?

EDIT:
If i use the class icon in css i change the parent of the star icons while they continue with 1em x 1em size.
screenshot with changes in icon

答:
To increase the size of the rating icons, we can use font-size. Using height and width will not work as it increases the size of the container they're in.

For example:

```<code><Rating
    name="rating"
    value={starValue}
    precision={0.1}
    size="large"
    readOnly
    sx={{
        fontSize: "4rem"
    }}
/>
</code>```

will increase the size of the icon further than just .MuiRating-sizeLarge which is their size if you set size="large". For reference, that size is about 1.8rem.

Title: How to enlarge Material-ui Rating icons

Body:
I am using npm to show develop a widget.
I want to use material-ui Ratin component and I have integrate it. But when I place the widget in a webpage, it has a html font-size: 62.5%, so the component is too small because in the icon style, there are a 1em unit in height and in width.
screenshot.

This is my code:

import React from 'react';
import Rating from '@material-ui/lab/Rating';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import { withStyles } from '@material-ui/core/styles';
import StarOutlineIcon from '@material-ui/icons/StarOutline';

const styles = theme => ({
  iconFilled:{
    color:theme.palette.primary.main,
  },
  iconEmpty:{
    color:theme.palette.primary.main
  }
})

class SimpleRating extends React.Component{

  state = {
    disabled: false,
    rating: 0,
    opinion: "",
  };

  changeRating(event, newRating) {
    this.setState({
      rating: newRating,
      disabled: true
    });

    this.props.send_rating(newRating)
  }

  defaultLabelText(value) {
    let text="sin calificación"
    if (value===1){
      text = "una estrella"
    }
    else if (value>1 && value<=5) {
      text = ""+ value + " estrellas"
    }
    return(text)
  }

  render() {
  const { classes } = this.props;
  return (

      <Box component="fieldset" mb={3} borderColor="transparent">
        <Typography component="legend"></Typography>
        <Rating
          classes={{
            iconFilled: classes.iconFilled,
            iconEmpty: classes.iconEmpty
          }}
          emptyIcon = {<StarOutlineIcon></StarOutlineIcon>}
          name={"rating_"+this.props.number}
          disabled={this.state.disabled}
          getLabelText={this.defaultLabelText.bind(this)}
          onChange={this.changeRating.bind(this)}
          value={this.state.rating}
        />
      </Box>

  );
    }
}

export default withStyles(styles)(SimpleRating);

Althougth I have been able to change the color with the styles, I cannot modify that down.
How can I change that properties of the icon?

EDIT:
If i use the class icon in css i change the parent of the star icons while they continue with 1em x 1em size.
screenshot with changes in icon

Body:
To increase the size of the rating icons, we can use font-size. Using height and width will not work as it increases the size of the container they're in.

For example:

<Rating
    name="rating"
    value={starValue}
    precision={0.1}
    size="large"
    readOnly
    sx={{
        fontSize: "4rem"
    }}
/>

will increase the size of the icon further than just .MuiRating-sizeLarge which is their size if you set size="large". For reference, that size is about 1.8rem.


问:
When I am trying to import a custom hook function I am getting a typescript error
I am trying to import my custom hook function(RegisterUser) on my register page. but when I am trying to import like this const { RegisterUser } = UseFirebase() I am getting an error which is const RegisterUser: any Property 'RegisterUser' does not exist on type 'readonly [(email: string, password: string, name: string, history: any) => Promise<void>]'.

This is my custom hook function.

```<code>export default function UseFirebase() {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()

    // REGISTER WITH EMAIL AND PASSWORD
    const RegisterUser = async (email: string, password: string, name: string, history: any) => {
        setIsLoading(true)
        const userCredential = await createUserWithEmailAndPassword(auth, email, password)

        const newUser = {
            email,
            displayName: name
        };

        setUser(newUser);
        setError('')

        // Pass userCredential.user instead of auth.currentUser
        updateProfile(userCredential.user, {
            displayName: name
        }).then(() => { }).catch((error) => { });
        history.replace('/');
    }

    return [RegisterUser] as const

}
</code>```

Can anyone help me, please? How can I solve the error?

答:
I'm not sure what you are trying to do but you typed your component as React.FunctionComponent<IUseFirebaseProps> but you returning [RegisterUser] as const and RegisterUser is not the correct return type for React.FunctionComponent<IUseFirebaseProps> or React.ReactElement<any, any> | null.

If you are trying to make a custom hook, you should remove React.FunctionComponent<IUseFirebaseProps> and React.ReactElement<any, any> | null which aren't necessary in a custom hook.

Also, a custom hook don't need to receive props of the type React.PropsWithChildren<IUseFirebaseProps>, maybe just use IUseFirebaseProps as a normal function parameter.

I'm guessing here, but you probably need something like this:

// type for the RegisterUserFunction
type RegisterUserFunction = (
  email: string,
  password: string,
  name: string,
  history: any
) => Promise<void>;

const UseFirebase = (
  props: IUseFirebaseProps, // it's not the props from a component, but more like a normal function parameter
  context?: any
): [RegisterUserFunction] => {
  // other hooks

  // REGISTER WITH EMAIL AND PASSWORD
  const RegisterUser: RegisterUserFunction = async (
    email: string,
    password: string,
    name: string,
    history: any
  ) => {
    // your function
  };

  return [RegisterUser]; // no need to use as const
};
```

Body:
I am trying to import my custom hook function(RegisterUser) on my register page. but when I am trying to import like this const { RegisterUser } = UseFirebase() I am getting an error which is const RegisterUser: any Property 'RegisterUser' does not exist on type 'readonly [(email: string, password: string, name: string, history: any) => Promise<void>]'.

This is my custom hook function.

export default function UseFirebase() {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()

    // REGISTER WITH EMAIL AND PASSWORD
    const RegisterUser = async (email: string, password: string, name: string, history: any) => {
        setIsLoading(true)
        const userCredential = await createUserWithEmailAndPassword(auth, email, password)

        const newUser = {
            email,
            displayName: name
        };

        setUser(newUser);
        setError('')

        // Pass userCredential.user instead of auth.currentUser
        updateProfile(userCredential.user, {
            displayName: name
        }).then(() => { }).catch((error) => { });
        history.replace('/');
    }

    return [RegisterUser] as const

}

Can anyone help me, please? How can I solve the error?


问:
When access to directmessage in twitter4j, an error shows "unable to parse '3577866941' as integer"
I have set the value of ACCESS_TOKEN,ACCESSTOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET which I got from dev.twitter but it crashes when the application runs.I use twitter4j-core-2.1.8-SNAPSHOT.jar as library.The code is given bellow.

```<code>public ResponseList<DirectMessage> dmList=null;
public static AccessToken token = new AccessToken(ACCESS_TOKEN, ACCESSTOKEN_SECRET);
TwitterFactory factory = new TwitterFactory();
twitter = factory.getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(token);
try {
    dmList = twitter.getDirectMessages(new Paging(1,15));
} catch (TwitterException e) {
    e.printStackTrace();
}
</code>```

Thanks.

答: Twitter userID and tweetID are not 32 bit integers. They recently upgraded them to 64bit, maybe your library is out of date ? </p>

ContentLicense: CC BY-SA 3.0

Body:
I have set the value of ACCESS_TOKEN,ACCESSTOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET which I got from dev.twitter but it crashes when the application runs.I use twitter4j-core-2.1.8-SNAPSHOT.jar as library.The code is given bellow.

public ResponseList<DirectMessage> dmList=null;
public static AccessToken token = new AccessToken(ACCESS_TOKEN, ACCESSTOKEN_SECRET);
TwitterFactory factory = new TwitterFactory();
twitter = factory.getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(token);
try {
    dmList = twitter.getDirectMessages(new Paging(1,15));
} catch (TwitterException e) {
    e.printStackTrace();
}

Thanks.


问:
Android designer render problem with TextInputLayout: java.lang.IllegalArgumentException: weight is out of range of [0, 1000]
Upon opening Android Studio today, I was greeted with a surprise - I could not see the preview of my layout:

I thought it would just be a simple fix of:

Reloading the designer

Cleaning and building the project

Invalidating caches and restarting

Although none of these have fixed the issue.

I have also went through other people having render issues and have tried various solutions although I'm still encountering the problem.

The strange thing is, whenever I remove the TextInputLayout widgets from my layout, the render problem disappears:

(Below is one of the layouts which is causing the problem.)

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragmentNewCanvas_rootLayout"
    tools:context=".fragments.newcanvas.NewCanvasFragment">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/fragmentNewCanvas_projectTitleTextInputLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:hint="@string/fragmentNewCanvas_project_name_str"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/fragmentNewCanvas_projectTitleTextInputEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/fragmentNewCanvas_spanCountTextInputLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:hint="@string/fragmentNewCanvas_span_count_str"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fragmentNewCanvas_projectTitleTextInputLayout">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/fragmentNewCanvas_spanCountTextInputEditText"
            android:inputType="number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/fragmentNewCanvas_doneButton"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="24dp"
        android:text="@string/str_button_done"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Here is a gif demonstrating the problem:

Layouts which do not contain a TextInputLayout render fine, but those that do are causing problems.

Stacktrace:

```<code>java.lang.IllegalArgumentException: weight is out of range of [0, 1000] (too low)
    at com.android.internal.util.Preconditions.checkArgumentInRange(Preconditions.java:527)
    at android.graphics.Typeface.create_Original(Typeface.java:979)
    at android.graphics.Typeface_Delegate.create(Typeface_Delegate.java:123)
    at android.graphics.Typeface.create(Typeface.java:979)
    at com.google.android.material.internal.CollapsingTextHelper.maybeCloneWithAdjustment(CollapsingTextHelper.java:532)
    at com.google.android.material.internal.CollapsingTextHelper.setCollapsedTypefaceInternal(CollapsingTextHelper.java:475)
    at com.google.android.material.internal.CollapsingTextHelper.setTypefaces(CollapsingTextHelper.java:459)
    at com.google.android.material.textfield.TextInputLayout.setEditText(TextInputLayout.java:1467)
    at com.google.android.material.textfield.TextInputLayout.addView(TextInputLayout.java:888)
    at android.view.ViewGroup.addView(ViewGroup.java:5048)
    at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1131)
    at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:1101)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
    at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1130)
    at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:1101)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:505)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:361)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:436)
    at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:121)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:727)
    at com.android.tools.idea.rendering.RenderTask.lambda$inflate$7(RenderTask.java:883)
    at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:187)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
</code>```

If anyone has a solution it would be greatly appreciated.

答:
Found a temporary workaround:

Change theme from Material3 to MaterialComponents

Will be waiting for a bugfix.

Body:
Upon opening Android Studio today, I was greeted with a surprise - I could not see the preview of my layout:

I thought it would just be a simple fix of:

Reloading the designer

Cleaning and building the project

Invalidating caches and restarting

Although none of these have fixed the issue.

I have also went through other people having render issues and have tried various solutions although I'm still encountering the problem.

The strange thing is, whenever I remove the TextInputLayout widgets from my layout, the render problem disappears:

(Below is one of the layouts which is causing the problem.)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragmentNewCanvas_rootLayout"
    tools:context=".fragments.newcanvas.NewCanvasFragment">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/fragmentNewCanvas_projectTitleTextInputLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:hint="@string/fragmentNewCanvas_project_name_str"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/fragmentNewCanvas_projectTitleTextInputEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/fragmentNewCanvas_spanCountTextInputLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:hint="@string/fragmentNewCanvas_span_count_str"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fragmentNewCanvas_projectTitleTextInputLayout">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/fragmentNewCanvas_spanCountTextInputEditText"
            android:inputType="number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/fragmentNewCanvas_doneButton"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="24dp"
        android:text="@string/str_button_done"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here is a gif demonstrating the problem:

Layouts which do not contain a TextInputLayout render fine, but those that do are causing problems.

Stacktrace:

java.lang.IllegalArgumentException: weight is out of range of [0, 1000] (too low)
    at com.android.internal.util.Preconditions.checkArgumentInRange(Preconditions.java:527)
    at android.graphics.Typeface.create_Original(Typeface.java:979)
    at android.graphics.Typeface_Delegate.create(Typeface_Delegate.java:123)
    at android.graphics.Typeface.create(Typeface.java:979)
    at com.google.android.material.internal.CollapsingTextHelper.maybeCloneWithAdjustment(CollapsingTextHelper.java:532)
    at com.google.android.material.internal.CollapsingTextHelper.setCollapsedTypefaceInternal(CollapsingTextHelper.java:475)
    at com.google.android.material.internal.CollapsingTextHelper.setTypefaces(CollapsingTextHelper.java:459)
    at com.google.android.material.textfield.TextInputLayout.setEditText(TextInputLayout.java:1467)
    at com.google.android.material.textfield.TextInputLayout.addView(TextInputLayout.java:888)
    at android.view.ViewGroup.addView(ViewGroup.java:5048)
    at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1131)
    at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:1101)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
    at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1130)
    at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:1101)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:505)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:361)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:436)
    at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:121)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:727)
    at com.android.tools.idea.rendering.RenderTask.lambda$inflate$7(RenderTask.java:883)
    at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:187)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)

If anyone has a solution it would be greatly appreciated.


问:
Replacing values in entire dataframe based on dictionary
I have a large dataframe in which I want to change every value based on a dictionary. Currently I am using a loop:

```<code>for column in df.columns:
     df = df.replace({column: dictionary})
</code>```

This works but it is pretty slow. This single for loop takes around 90% of the time that it takes my entire code to run. Is there a faster method using loc, map or replace?

There are lots of other questions like this already but it seems pretty much everyone else is just trying to change individual columns rather than the entire dataframe.

I'm using Spyder with Python 3.9 on Windows. Thanks!

Edit: I found a way to make it faster by switching rows and columns. Previously I had lots of columns and few rows, now that it's the other way around the code is a lot faster. Still, is there a way to replace values in the entire dataframe rather than just individual columns?

答:
Is there a way to replace values in the entire dataframe rather than just individual columns?

Use:

```<code>df = df.replace(dictionary)
</code>```

Body:
I have a large dataframe in which I want to change every value based on a dictionary. Currently I am using a loop:

for column in df.columns:
     df = df.replace({column: dictionary})

This works but it is pretty slow. This single for loop takes around 90% of the time that it takes my entire code to run. Is there a faster method using loc, map or replace?

There are lots of other questions like this already but it seems pretty much everyone else is just trying to change individual columns rather than the entire dataframe.

I'm using Spyder with Python 3.9 on Windows. Thanks!

Edit: I found a way to make it faster by switching rows and columns. Previously I had lots of columns and few rows, now that it's the other way around the code is a lot faster. Still, is there a way to replace values in the entire dataframe rather than just individual columns?

Body:
Is there a way to replace values in the entire dataframe rather than just individual columns?

Use:

df = df.replace(dictionary)


问:
Error with dimensionality when fitting a stateful RNN
I am fitting a stateful RNN with embedding layer to perform binary classification. I am having some confusion with the batch_size and batch_shape needed in the function APIs.

```<code>xtrain_padded.shape = (9600, 1403); xtest_padded.shape = (2400, 1403); ytest.shape = (2400,)
input_dim = size of tokenizer word dictionary
output_dim = 100 from GloVe_100d embeddings
number of SimpleRNN layer units = 200

h0: initial hidden states sampled from random uniform.
h0 object has the same shape as RNN layer hidden states obtained when return_state = True.
</code>```

The model structure:

```<code>batch_size = 2400  # highest common factor of xtrain and xtest
inp= Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out= Embedding(input_dim, output_dim, input_length= input_length,
                         weights= [Emat], trainable= False, name= 'embedding')(inp)

rnn= SimpleRNN(200, return_sequences= True, return_state= True, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

h_0 = tf.random.uniform((batch_size, input_length, 200))
rnn_out, rnn_state = rnn(emb_out, initial_state=h0)
mod_out= Dense(1, activation= 'sigmoid')(rnn_out)
# Extract the y_t's and h_t's:
model = Model(inputs=inp, outputs=[mod_out, rnn_out])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           [(2400, 1403)]            0
_________________________________________________________________
embedding (Embedding)        (2400, 1403, 100)         4348900
_________________________________________________________________
simpleRNN (SimpleRNN)        [(2400, 1403, 200), (2400 60200
_________________________________________________________________
dense_3 (Dense)              (2400, 1403, 1)           201
</code>```

No issue when I fit the test data to model using the model API:

```<code>mod_out_allsteps, rnn_ht= model(xte_pad)  # Same as the 2 items from model.predict(xte_pad)
print(mod_out_allsteps.shape, rnn_ht.shape)
>> (2400, 1403, 1) (2400, 1403, 200)
</code>```

However it raised a ValueError regarding unequal dimensions when I use model.fit.

```<code>model.fit(xte_pad, yte, epochs =1, batch_size = batch_size, verbose = 1)
>>
    ValueError: Dimensions must be equal, but are 2400 and 1403 for '{{node binary_crossentropy_1/mul}} = Mul[T=DT_FLOAT](binary_crossentropy_1/Cast, binary_crossentropy_1/Log)' with input shapes: [2400,1], [2400,1403,200].

</code>```

The error seems to suggest the model has confused the returned hidden states rnn_ht shaped [2400,1403,200] with something else when fitting the data. However I am going to need these states for computing the gradients on the initial hidden states i.e.

for t = 1,..., 1403.

I am confused with the dimensions in stateful RNNs:

If stateful = True, are we constructing the model based on one mini-batch?

i.e. the first index in Output Shape of each layer will be the batch_size?

What is the batch_shape to be set in the first layer (Input)? Have I set it right?

Thank you in advance for helping with the error and my confusion!

Update:

```<code>batch_size = 2400  # highest common factor of xtrain and xtest
input_length = 1403
output_dim = 100
inp= tf.keras.layers.Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out=  tf.keras.layers.Embedding(500, output_dim, input_length= input_length, trainable= False, name= 'embedding')(inp)

rnn=  tf.keras.layers.SimpleRNN(200, return_sequences= True, return_state= False, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')
rnn_ht= rnn(emb_out)  # hidden states at all steps
print(rnn_ht.shape)
>>>
(2400, 1403, 200)

mod_out= Dense(1, activation= 'sigmoid')(Flatten()(rnn_ht))
# Extract the y_t's and h_t's:
model =  tf.keras.Model(inputs=inp, outputs=[mod_out, rnn_ht])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           [(2400, 1403)]            0
_________________________________________________________________
embedding (Embedding)        (2400, 1403, 100)         50000
_________________________________________________________________
simpleRNN (SimpleRNN)        (2400, 1403, 200)         60200
_________________________________________________________________
flatten_4 (Flatten)          (2400, 280600)            0
_________________________________________________________________
dense_4 (Dense)              (2400, 1)                 280601

mod_out_allsteps, rnn_ht= model_ht(xte_pad)
print(mod_out_allsteps.shape, rnn_ht.shape)
>>>
(2400, 1) (2400, 1403, 200)

But the error with ```model.fit``` persists.

</code>```

答:
Look at the last layer in your model summary. Since you set the parameter return_sequences to True in the RNN layer, you are getting a sequence with the same number of time steps as your input and an output space of 200 for each timestep, hence the shape (2400, 1403, 200), where 2400 is the batch size. If you set this parameter to False, everything should work, since your labels have the shape (2400, 1).

Working example:

```<code>import tensorflow as tf

batch_size = 2400  # highest common factor of xtrain and xtest
input_length = 1403
output_dim = 100
inp= tf.keras.layers.Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out=  tf.keras.layers.Embedding(500, output_dim, input_length= input_length, trainable= False, name= 'embedding')(inp)

rnn=  tf.keras.layers.SimpleRNN(200, return_sequences= False, return_state= True, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

rnn_out, rnn_state = rnn(emb_out)
mod_out=  tf.keras.layers.Dense(1, activation= 'sigmoid')(rnn_out)
# Extract the y_t's and h_t's:
model =  tf.keras.Model(inputs=inp, outputs=[mod_out, rnn_out])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()
</code>```

where the first output is your binary decision.

Update 1: with Flatten:

import tensorflow as tf

batch_size = 2400  # highest common factor of xtrain and xtest
input_length = 1403
output_dim = 100
inp= tf.keras.layers.Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out=  tf.keras.layers.Embedding(500, output_dim, input_length= input_length, trainable= False, name= 'embedding')(inp)

rnn=  tf.keras.layers.SimpleRNN(200, return_sequences= True, return_state= True, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

rnn_out, rnn_state = rnn(emb_out)
mod_out=  tf.keras.layers.Dense(1, activation= 'sigmoid')(tf.keras.layers.Flatten()(rnn_out))
# Extract the y_t's and h_t's:
model =  tf.keras.Model(inputs=inp, outputs=[mod_out, rnn_out])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()
```

Body:
I am fitting a stateful RNN with embedding layer to perform binary classification. I am having some confusion with the batch_size and batch_shape needed in the function APIs.

xtrain_padded.shape = (9600, 1403); xtest_padded.shape = (2400, 1403); ytest.shape = (2400,)
input_dim = size of tokenizer word dictionary
output_dim = 100 from GloVe_100d embeddings
number of SimpleRNN layer units = 200

h0: initial hidden states sampled from random uniform.
h0 object has the same shape as RNN layer hidden states obtained when return_state = True.

The model structure:

batch_size = 2400  # highest common factor of xtrain and xtest
inp= Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out= Embedding(input_dim, output_dim, input_length= input_length,
                         weights= [Emat], trainable= False, name= 'embedding')(inp)

rnn= SimpleRNN(200, return_sequences= True, return_state= True, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

h_0 = tf.random.uniform((batch_size, input_length, 200))
rnn_out, rnn_state = rnn(emb_out, initial_state=h0)
mod_out= Dense(1, activation= 'sigmoid')(rnn_out)
# Extract the y_t's and h_t's:
model = Model(inputs=inp, outputs=[mod_out, rnn_out])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           [(2400, 1403)]            0
_________________________________________________________________
embedding (Embedding)        (2400, 1403, 100)         4348900
_________________________________________________________________
simpleRNN (SimpleRNN)        [(2400, 1403, 200), (2400 60200
_________________________________________________________________
dense_3 (Dense)              (2400, 1403, 1)           201

No issue when I fit the test data to model using the model API:

mod_out_allsteps, rnn_ht= model(xte_pad)  # Same as the 2 items from model.predict(xte_pad)
print(mod_out_allsteps.shape, rnn_ht.shape)
>> (2400, 1403, 1) (2400, 1403, 200)

However it raised a ValueError regarding unequal dimensions when I use model.fit.

model.fit(xte_pad, yte, epochs =1, batch_size = batch_size, verbose = 1)
>>
    ValueError: Dimensions must be equal, but are 2400 and 1403 for '{{node binary_crossentropy_1/mul}} = Mul[T=DT_FLOAT](binary_crossentropy_1/Cast, binary_crossentropy_1/Log)' with input shapes: [2400,1], [2400,1403,200].

The error seems to suggest the model has confused the returned hidden states rnn_ht shaped [2400,1403,200] with something else when fitting the data. However I am going to need these states for computing the gradients on the initial hidden states i.e.

for t = 1,..., 1403.

I am confused with the dimensions in stateful RNNs:

If stateful = True, are we constructing the model based on one mini-batch?

i.e. the first index in Output Shape of each layer will be the batch_size?

What is the batch_shape to be set in the first layer (Input)? Have I set it right?

Thank you in advance for helping with the error and my confusion!

Update:

batch_size = 2400  # highest common factor of xtrain and xtest
input_length = 1403
output_dim = 100
inp= tf.keras.layers.Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out=  tf.keras.layers.Embedding(500, output_dim, input_length= input_length, trainable= False, name= 'embedding')(inp)

rnn=  tf.keras.layers.SimpleRNN(200, return_sequences= True, return_state= False, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')
rnn_ht= rnn(emb_out)  # hidden states at all steps
print(rnn_ht.shape)
>>>
(2400, 1403, 200)

mod_out= Dense(1, activation= 'sigmoid')(Flatten()(rnn_ht))
# Extract the y_t's and h_t's:
model =  tf.keras.Model(inputs=inp, outputs=[mod_out, rnn_ht])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           [(2400, 1403)]            0
_________________________________________________________________
embedding (Embedding)        (2400, 1403, 100)         50000
_________________________________________________________________
simpleRNN (SimpleRNN)        (2400, 1403, 200)         60200
_________________________________________________________________
flatten_4 (Flatten)          (2400, 280600)            0
_________________________________________________________________
dense_4 (Dense)              (2400, 1)                 280601

mod_out_allsteps, rnn_ht= model_ht(xte_pad)
print(mod_out_allsteps.shape, rnn_ht.shape)
>>>
(2400, 1) (2400, 1403, 200)

But the error with ```model.fit``` persists.

Body:
Look at the last layer in your model summary. Since you set the parameter return_sequences to True in the RNN layer, you are getting a sequence with the same number of time steps as your input and an output space of 200 for each timestep, hence the shape (2400, 1403, 200), where 2400 is the batch size. If you set this parameter to False, everything should work, since your labels have the shape (2400, 1).

Working example:

import tensorflow as tf

batch_size = 2400  # highest common factor of xtrain and xtest
input_length = 1403
output_dim = 100
inp= tf.keras.layers.Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out=  tf.keras.layers.Embedding(500, output_dim, input_length= input_length, trainable= False, name= 'embedding')(inp)

rnn=  tf.keras.layers.SimpleRNN(200, return_sequences= False, return_state= True, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

rnn_out, rnn_state = rnn(emb_out)
mod_out=  tf.keras.layers.Dense(1, activation= 'sigmoid')(rnn_out)
# Extract the y_t's and h_t's:
model =  tf.keras.Model(inputs=inp, outputs=[mod_out, rnn_out])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()

where the first output is your binary decision.

Update 1: with Flatten:

import tensorflow as tf

batch_size = 2400  # highest common factor of xtrain and xtest
input_length = 1403
output_dim = 100
inp= tf.keras.layers.Input(batch_shape= (batch_size, input_length), name= 'input')
emb_out=  tf.keras.layers.Embedding(500, output_dim, input_length= input_length, trainable= False, name= 'embedding')(inp)

rnn=  tf.keras.layers.SimpleRNN(200, return_sequences= True, return_state= True, stateful= True,
              batch_size= (batch_size, input_length, 100), name= 'simpleRNN')

rnn_out, rnn_state = rnn(emb_out)
mod_out=  tf.keras.layers.Dense(1, activation= 'sigmoid')(tf.keras.layers.Flatten()(rnn_out))
# Extract the y_t's and h_t's:
model =  tf.keras.Model(inputs=inp, outputs=[mod_out, rnn_out])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
model.summary()


问:
C++ shared_ptr and mutex
I'm new to C++ and I have to following scenario:

main.cpp

```<code>#include "Foo.h"
#include "Bar.h"

int main() {
    Bar bar{};
    auto bar_ptr = std::make_shared<Bar>(bar);

    for (int i = 0; i < 10; i++) {
        Foo foo{bar_ptr};
    }

    return 0;
}
</code>```

I want 10 Instances of Class Foo to share 1 Instance of Class Bar. Each Instance of Class Foo will run in a separate Thread. I want the shared Instance of Class Bar only to be accessed by one Instance of Foo at a time. That's why I wanted to add a std::mutex to Foo. This seems to conflict with std::mutex not being copyable/moveable. What is the correct way to use a mutex with a shared_ptr?

Foo.h

```<code>#include <memory>
#include <utility>
#include "Bar.h"

class Foo {
    std::shared_ptr<Bar> bar_ptr;

public:
    explicit Foo(std::shared_ptr<Bar> bar_ptr){
        this->bar_ptr = std::move(bar_ptr);
    }
};
</code>```

Bar.h

```<code>#include <mutex>

class Bar {
    std::mutex mutex{};

};
</code>```

答:
std::mutex is a move-only type, so you can't copy it.

In your main function you are creating a Bar, and then trying to create a std::shared_ptr by copying that instance of Bar.

Instead, just use std::make_shared<Bar>() to create a shared_ptr to a bar with the default constructor.

```<code>#include "Foo.h"
#include "Bar.h"

int main() {
    auto bar_ptr = std::make_shared<Bar>();

    for (int i = 0; i < 10; i++) {
        Foo foo{bar_ptr};
    }

    return 0;
}
</code>```

To clarify, the arguments passed to make_shared are forwarded to the constructor of the class. If you pass a Bar& it will try to use the copy constructor.

If you pass nothing it will use the default constructor.

If Bars constructor takes arguments in your real use-case, pass the arguments to make_shared.

```<code>#include <memory>
#include <utility>
#include <mutex>

class Bar {
    public:
    Bar(int i) : value(i) {}
    private:
    std::mutex mutex{};
    int value;
};

class Foo {
    std::shared_ptr<Bar> bar_ptr;

public:
    // Use the initializer list when possible
    // Otherwise we first default-construct then assign
    explicit Foo(std::shared_ptr<Bar> ptr) : bar_ptr(std::move(ptr)) {}
};

int main() {
    auto bar_ptr = std::make_shared<Bar>(5);

    for (int i = 0; i < 10; i++) {
        Foo foo{bar_ptr};
    }

    return 0;
}
</code>```

Title: C++ shared_ptr and mutex

Body:
I'm new to C++ and I have to following scenario:

main.cpp

#include "Foo.h"
#include "Bar.h"

int main() {
    Bar bar{};
    auto bar_ptr = std::make_shared<Bar>(bar);

    for (int i = 0; i < 10; i++) {
        Foo foo{bar_ptr};
    }

    return 0;
}

I want 10 Instances of Class Foo to share 1 Instance of Class Bar. Each Instance of Class Foo will run in a separate Thread. I want the shared Instance of Class Bar only to be accessed by one Instance of Foo at a time. That's why I wanted to add a std::mutex to Foo. This seems to conflict with std::mutex not being copyable/moveable. What is the correct way to use a mutex with a shared_ptr?

Foo.h

#include <memory>
#include <utility>
#include "Bar.h"

class Foo {
    std::shared_ptr<Bar> bar_ptr;

public:
    explicit Foo(std::shared_ptr<Bar> bar_ptr){
        this->bar_ptr = std::move(bar_ptr);
    }
};

Bar.h

#include <mutex>

class Bar {
    std::mutex mutex{};

};

Body:
std::mutex is a move-only type, so you can't copy it.

In your main function you are creating a Bar, and then trying to create a std::shared_ptr by copying that instance of Bar.

Instead, just use std::make_shared<Bar>() to create a shared_ptr to a bar with the default constructor.

#include "Foo.h"
#include "Bar.h"

int main() {
    auto bar_ptr = std::make_shared<Bar>();

    for (int i = 0; i < 10; i++) {
        Foo foo{bar_ptr};
    }

    return 0;
}

To clarify, the arguments passed to make_shared are forwarded to the constructor of the class. If you pass a Bar& it will try to use the copy constructor.

If you pass nothing it will use the default constructor.

If Bars constructor takes arguments in your real use-case, pass the arguments to make_shared.

#include <memory>
#include <utility>
#include <mutex>

class Bar {
    public:
    Bar(int i) : value(i) {}
    private:
    std::mutex mutex{};
    int value;
};

class Foo {
    std::shared_ptr<Bar> bar_ptr;

public:
    // Use the initializer list when possible
    // Otherwise we first default-construct then assign
    explicit Foo(std::shared_ptr<Bar> ptr) : bar_ptr(std::move(ptr)) {}
};

int main() {
    auto bar_ptr = std::make_shared<Bar>(5);

    for (int i = 0; i < 10; i++) {
        Foo foo{bar_ptr};
    }

    return 0;
}


问:
FastAPI WebSocket replication
I have implemented a simple WebSocket proxy with FastAPI (using this example)

The application target is to just pass through all messages it gets to its active connections  (proxy).

It works well only with a single instance because it keeps active WebSocket connections in memory. And memory is not shared when there is more than one instance.

My naive approach was to solve it by keeping active connections in some shared storage (Redis). But I was stuck with pickling it.

Here is the complete app:

```<code>import pickle

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from collections import defaultdict
import redis

app = FastAPI()
rds = redis.StrictRedis('localhost')

class ConnectionManager:
    def __init__(self):
        self.active_connections = defaultdict(dict)

    async def connect(self, websocket: WebSocket, application: str, client_id: str):
        await websocket.accept()
        if application not in self.active_connections:
            self.active_connections[application] = defaultdict(list)

        self.active_connections[application][client_id].append(websocket)

        #### this is my attempt to store connections ####
        rds.set('connections', pickle.dumps(self.active_connections))

    def disconnect(self, websocket: WebSocket, application: str, client_id: str):
        self.active_connections[application][client_id].remove(websocket)

    async def broadcast(self, message: dict, application: str, client_id: str):
        for connection in self.active_connections[application][client_id]:
            try:
                await connection.send_json(message)
                print(f"sent {message}")
            except Exception as e:
                pass

manager = ConnectionManager()

@app.websocket("/ws/channel/{application}/{client_id}/")
async def websocket_endpoint(websocket: WebSocket, application: str, client_id: str):
    await manager.connect(websocket, application, client_id)
    while True:
        try:
            data = await websocket.receive_json()
            print(f"received: {data}")
            await manager.broadcast(data, application, client_id)
        except WebSocketDisconnect:
            manager.disconnect(websocket, application, client_id)
        except RuntimeError:
            break

if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host='0.0.0.0', port=8005)
</code>```

However, pickling websocket connection was not successful:

```<code>AttributeError: Can't pickle local object 'FastAPI.setup.<locals>.openapi'
</code>```

What is the proper way to have WebSocket connections stored across the application instances?

UPD The actual solution per @AKX answer.

Each instance of the server is subscribed to Redis pubsub and tries to send the received message to all its connected clients.

Since one client cannot be connected to several instances - each message should be delivered to each client only once

```<code>import json
import asyncio

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from collections import defaultdict
import redis

app = FastAPI()
rds = redis.StrictRedis('localhost')

class ConnectionManager:
    def __init__(self):
        self.active_connections = defaultdict(dict)

    async def connect(self, websocket: WebSocket, application: str, client_id: str):
        await websocket.accept()
        if application not in self.active_connections:
            self.active_connections[application] = defaultdict(list)

        self.active_connections[application][client_id].append(websocket)

    def disconnect(self, websocket: WebSocket, application: str, client_id: str):
        self.active_connections[application][client_id].remove(websocket)

    async def broadcast(self, message: dict, application: str, client_id: str):
        for connection in self.active_connections[application][client_id]:
            try:
                await connection.send_json(message)
                print(f"sent {message}")
            except Exception as e:
                pass

    async def consume(self):
        print("started to consume")
        sub = rds.pubsub()
        sub.subscribe('channel')
        while True:
            await asyncio.sleep(0.01)
            message = sub.get_message(ignore_subscribe_messages=True)
            if message is not None and isinstance(message, dict):
                msg = json.loads(message.get('data'))
                await self.broadcast(msg['message'], msg['application'], msg['client_id'])

manager = ConnectionManager()

@app.on_event("startup")
async def subscribe():
    asyncio.create_task(manager.consume())

@app.websocket("/ws/channel/{application}/{client_id}/")
async def websocket_endpoint(websocket: WebSocket, application: str, client_id: str):
    await manager.connect(websocket, application, client_id)
    while True:
        try:
            data = await websocket.receive_json()
            print(f"received: {data}")
            rds.publish(
                'channel',
                json.dumps({
                   'application': application,
                   'client_id': client_id,
                   'message': data
                })
            )
        except WebSocketDisconnect:
            manager.disconnect(websocket, application, client_id)
        except RuntimeError:
            break

if __name__ == '__main__':  # pragma: no cover
    import uvicorn

    uvicorn.run(app, host='0.0.0.0', port=8005)
</code>```

答:
What is the proper way to have WebSocket connections stored across the application instances?

There is no practical way for multiple processes to share websocket connections that I know of. As you noticed, you can't pickle the connections (not least because you can't pickle the actual OS-level file descriptor that represents the network connection). You can send file descriptors to other processes with some POSIX magic, but even so, you'd also need to make sure the processes know the state of the websocket and don't e.g. race at sending or receiving data.

I would probably redesign things to have a single process that manages the websocket connections and e.g. uses Redis (since you already have it) pubsub or streams to communicate with other multiple processes you have.

Title: FastAPI WebSocket replication

Body:
I have implemented a simple WebSocket proxy with FastAPI (using this example)

The application target is to just pass through all messages it gets to its active connections  (proxy).

It works well only with a single instance because it keeps active WebSocket connections in memory. And memory is not shared when there is more than one instance.

My naive approach was to solve it by keeping active connections in some shared storage (Redis). But I was stuck with pickling it.

Here is the complete app:

import pickle

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from collections import defaultdict
import redis

app = FastAPI()
rds = redis.StrictRedis('localhost')

class ConnectionManager:
    def __init__(self):
        self.active_connections = defaultdict(dict)

    async def connect(self, websocket: WebSocket, application: str, client_id: str):
        await websocket.accept()
        if application not in self.active_connections:
            self.active_connections[application] = defaultdict(list)

        self.active_connections[application][client_id].append(websocket)

        #### this is my attempt to store connections ####
        rds.set('connections', pickle.dumps(self.active_connections))

    def disconnect(self, websocket: WebSocket, application: str, client_id: str):
        self.active_connections[application][client_id].remove(websocket)

    async def broadcast(self, message: dict, application: str, client_id: str):
        for connection in self.active_connections[application][client_id]:
            try:
                await connection.send_json(message)
                print(f"sent {message}")
            except Exception as e:
                pass

manager = ConnectionManager()

@app.websocket("/ws/channel/{application}/{client_id}/")
async def websocket_endpoint(websocket: WebSocket, application: str, client_id: str):
    await manager.connect(websocket, application, client_id)
    while True:
        try:
            data = await websocket.receive_json()
            print(f"received: {data}")
            await manager.broadcast(data, application, client_id)
        except WebSocketDisconnect:
            manager.disconnect(websocket, application, client_id)
        except RuntimeError:
            break

if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app, host='0.0.0.0', port=8005)

However, pickling websocket connection was not successful:

AttributeError: Can't pickle local object 'FastAPI.setup.<locals>.openapi'

What is the proper way to have WebSocket connections stored across the application instances?

UPD The actual solution per @AKX answer.

Each instance of the server is subscribed to Redis pubsub and tries to send the received message to all its connected clients.

Since one client cannot be connected to several instances - each message should be delivered to each client only once

import json
import asyncio

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from collections import defaultdict
import redis

app = FastAPI()
rds = redis.StrictRedis('localhost')

class ConnectionManager:
    def __init__(self):
        self.active_connections = defaultdict(dict)

    async def connect(self, websocket: WebSocket, application: str, client_id: str):
        await websocket.accept()
        if application not in self.active_connections:
            self.active_connections[application] = defaultdict(list)

        self.active_connections[application][client_id].append(websocket)

    def disconnect(self, websocket: WebSocket, application: str, client_id: str):
        self.active_connections[application][client_id].remove(websocket)

    async def broadcast(self, message: dict, application: str, client_id: str):
        for connection in self.active_connections[application][client_id]:
            try:
                await connection.send_json(message)
                print(f"sent {message}")
            except Exception as e:
                pass

    async def consume(self):
        print("started to consume")
        sub = rds.pubsub()
        sub.subscribe('channel')
        while True:
            await asyncio.sleep(0.01)
            message = sub.get_message(ignore_subscribe_messages=True)
            if message is not None and isinstance(message, dict):
                msg = json.loads(message.get('data'))
                await self.broadcast(msg['message'], msg['application'], msg['client_id'])

manager = ConnectionManager()

@app.on_event("startup")
async def subscribe():
    asyncio.create_task(manager.consume())

@app.websocket("/ws/channel/{application}/{client_id}/")
async def websocket_endpoint(websocket: WebSocket, application: str, client_id: str):
    await manager.connect(websocket, application, client_id)
    while True:
        try:
            data = await websocket.receive_json()
            print(f"received: {data}")
            rds.publish(
                'channel',
                json.dumps({
                   'application': application,
                   'client_id': client_id,
                   'message': data
                })
            )
        except WebSocketDisconnect:
            manager.disconnect(websocket, application, client_id)
        except RuntimeError:
            break

if __name__ == '__main__':  # pragma: no cover
    import uvicorn

    uvicorn.run(app, host='0.0.0.0', port=8005)


问:
How to detect when a phone call is triggered when the application is up?
My application is a coupon shopping,users will download the coupons in phone and when completed they will be directed for the automatic cash payment.
If a user downloads 5 coupons and inbetween gets a call as it is iOS4 it goes to background.
So when we press the home button also the application goes to background by this behaviour.I have save few data and restore the coupons when the user quits the application by homebutton.
But in iOS 4 behaviour homebutton press and phone call interruptions shows the same behaviour and calls the same functions,how i could differentiate between the 2.
Please this is a tedious function,please help me.......</p>

答: iOS will not tell an app what caused an interruption such as a phone call, an SMS message, or a press of the home button. This is a deliberate design decision by Apple.  Apple expects apps to be designed to exhibit the same behavior no matter what caused the interruption.</p>


问:
BeautifulSoup Isn't Producing A Result
I'm trying to web scrape a site that gives play by plays live. In this example though, the game is over but I still want to scrape the play by play. But when I use the code below, I'm unable to produce any results. The url variable is the real link to the site.

```<code>import requests
import re
import json
from bs4 import BeautifulSoup

url = "http://pointstreak.com/baseball/gamelive/?gameid=483832"
r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')
game = soup.findAll('tr',class_ = "inning_1 pbp-bottom-border")

print(game)
</code>```

My result is []

Can anyone help guide me in the right direction so I can grab the data inside the tag. On a side note, I am new to this so I may be making a rookie mistake

答:
You'll have to grab the play by play from the final box score page. Quite easy since they put it in
 tags. you can let pandas do the work for you (it uses bs4 under the hood).

```<code>import pandas as pd

url = 'http://baseball.pointstreak.com/boxscore.html?gameid=514852'
dfs = pd.read_html(url)

for idx, df in enumerate(dfs):
    if df.iloc[0,0] == 'Top of 1st':
        startIdx = idx
        break

pbp = pd.concat(dfs[startIdx:])
</code>```

Output:

```<code>print(pbp)
                                      0                                                  1
0                            Top of 1st                                   Madison Mallards
1                        #55 E.J. Ranel  Foul, Ball, Ball, Swinging Strike, Ball, Foul,...
2                      #48 Ben Anderson  Ball, 48 Ben Anderson advances to 2nd (double ...
3                    #50 Justice Bigbie  Swinging Strike, Swinging Strike, 50 Justice B...
4                   #45 Austin Blazevic  45 Austin Blazevic putout (fly out to the shor...
..                                  ...                                                ...
5                Offensive Substitution              32 Zach Klapak subs for Kyle Simmons.
6                       #32 Zach Klapak  Ball, Swinging Strike, Called Strike, Ball, 32...
7                    #6 Brandon Seltzer  30 Kaeber Rog Scores Earned (6), 6 Brandon Sel...
8                        #20 Adam Frank  Called Strike, Ball, Ball, Called Strike, 20 A...
9   Runs: 1, Hits: 0, Errors: 0, LOB: 2                Runs: 1, Hits: 0, Errors: 0, LOB: 2

[120 rows x 2 columns]
</code>```

Title: BeautifulSoup Isn't Producing A Result

Body:
I'm trying to web scrape a site that gives play by plays live. In this example though, the game is over but I still want to scrape the play by play. But when I use the code below, I'm unable to produce any results. The url variable is the real link to the site.

import requests
import re
import json
from bs4 import BeautifulSoup

url = "http://pointstreak.com/baseball/gamelive/?gameid=483832"
r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')
game = soup.findAll('tr',class_ = "inning_1 pbp-bottom-border")

print(game)

My result is []

Can anyone help guide me in the right direction so I can grab the data inside the tag. On a side note, I am new to this so I may be making a rookie mistake

Body:
You'll have to grab the play by play from the final box score page. Quite easy since they put it in <table> tags. you can let pandas do the work for you (it uses bs4 under the hood).

import pandas as pd

url = 'http://baseball.pointstreak.com/boxscore.html?gameid=514852'
dfs = pd.read_html(url)

for idx, df in enumerate(dfs):
    if df.iloc[0,0] == 'Top of 1st':
        startIdx = idx
        break

pbp = pd.concat(dfs[startIdx:])

Output:

print(pbp)
                                      0                                                  1
0                            Top of 1st                                   Madison Mallards
1                        #55 E.J. Ranel  Foul, Ball, Ball, Swinging Strike, Ball, Foul,...
2                      #48 Ben Anderson  Ball, 48 Ben Anderson advances to 2nd (double ...
3                    #50 Justice Bigbie  Swinging Strike, Swinging Strike, 50 Justice B...
4                   #45 Austin Blazevic  45 Austin Blazevic putout (fly out to the shor...
..                                  ...                                                ...
5                Offensive Substitution              32 Zach Klapak subs for Kyle Simmons.
6                       #32 Zach Klapak  Ball, Swinging Strike, Called Strike, Ball, 32...
7                    #6 Brandon Seltzer  30 Kaeber Rog Scores Earned (6), 6 Brandon Sel...
8                        #20 Adam Frank  Called Strike, Ball, Ball, Called Strike, 20 A...
9   Runs: 1, Hits: 0, Errors: 0, LOB: 2                Runs: 1, Hits: 0, Errors: 0, LOB: 2

[120 rows x 2 columns]


问:
Dealing with an inaccurate system clock
I have a windows based system that sits on an Amazon EC2 instance. There is a known issue that Windows EC2 instances have problems keeping their system time in sync. I'll randomly log into the system and find that my system clock is anywhere from a couple seconds off (not too big of a deal...) to several minutes or even hours off (obviously a huge deal).

Considering that my site's prime objective is to issue out links to secured S3 content that is locked down by a considerably strict time limit (ie sometimes as little as 30 seconds to a minute), this is a huge issue for me. Scouring Amazon's help forums has yielded many answers that simply do not work and Amazon seems to be ignoring the issue claiming it's Windows related. Regardless, I've decided to take things into my own hands and not to wait on Amazon.

Things I've considered:

Creating a service that hits a list of time servers every hour or so, gets the current time, calculates the offset, and then uses this offset to generate accurate links. The downsides being that I need to have a substantial list of time servers so that they don't block me from hitting them too often. Also, if the time gets randomly fixed in the middle of one of these periods, my links will start breaking again.

Creating a Linux EC2 instance and finding some way of getting its internal time. I haven't read anything on how accurate their times are within EC2, but I would have to assume it's better that this nonsense.

Hosting my site elsewhere that has accurate clocks...

Are there any other options you can think of that I may have missed? I'm not really opposed to anything with the one exception being rewriting my site in another language so as to move away from Windows (it's a .Net MVC application currently).

Thanks in advance!

EDIT: Also of note, I can not use referrer based security as the plugins I'm utilizing that use these links don't 100% send the referrer in some browsers.

答:
you could try making an app on either your windows instance or a linux instance if you choose to go that way, and whenever you need to know what the time is send an api request to somewhere like this: http://worldtimeengine.com/api/ to get the current local time.

if you can't rely on the clock of the instance then get the time from somewhere else :)

Title: Dealing with an inaccurate system clock


问:
Error: LateInitializationError: Field 'sharedPreferences' has not been initialized. Flutter Verygoodcli web app

Error Initializing an already late variable.

In my app there is a composition_root.dart file that composes all the pages. I am migrating code to Flutter 2.10 with a verygoodcli app using verygoodanalysis.

Here is the Composition root:

class CompositionRoot {
  static late SharedPreferences _sharedPreferences;
  static late ILocalStore _localStore;
  static late String _baseUrl;
  static late Client _client;

  static void configure() {
    _localStore = LocalStore(_sharedPreferences);
    _client = Client();
    _baseUrl = 'http://localhost:3000';
  }

  static Widget composeAuthUI() {
    final IAuthApi _api = AuthApi(_baseUrl, _client);
    final _manager = AuthManager(_api);
    final _authCubit = AuthstateCubit(_localStore);
    final _signUpService = SignUpService(_api);

    return BlocProvider(
      create: (BuildContext context) => _authCubit,
      child: AuthPage(_manager, _signUpService),
    );
  }
}

```
<p>However when I run the code, I seem to get the following error message:</p>
<pre class="lang-sh prettyprint-override"><code>
Error: LateInitializationError: Field 'sharedPreferences' has not been
initialized.
    at Object.throw_ [as throw] (http://localhost:40837/dart_sdk.js:5067:11)
    at Function.get sharedPreferences [as sharedPreferences]
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:58
    :37)
    at Function.configure
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:88
    :118)
    at main
    (http://localhost:40837/packages/verygoodapp/main_development.dart.lib.js:45
    :38)
    at main (http://localhost:40837/web_entrypoint.dart.lib.js:36:29)
    at main.next (<anonymous>)

</code>```

How can I debug this errror also do you mind explaining whats going on, I can't seem to understand. The app is configured in the main_*.dart file before the UI is composed.

main_*.dart

void main() {
  CompositionRoot.configure();
  bootstrap(() => const App());
}

```
<p>Our App Widget Class:</p>
<pre class="lang-dart prettyprint-override"><code>class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)),
        colorScheme: ColorScheme.fromSwatch(
          accentColor: const Color.fromARGB(255, 190, 27, 27),
        ),
      ),
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      home: CompositionRoot.composeAuthUI(),
    );
  }
}

</code>```

I can't seem to understand please help. Thanks in advance.

答:
_sharedPreferences has not been initialized. Meaning it is storing none and you are trying to use it

Try this

```<code>_sharedPreferences = await SharedPreferences.getInstance();
_localStore = LocalStore(_sharedPreferences);
</code>```

Then you are good to go

Body:
Error Initializing an already late variable.

In my app there is a composition_root.dart file that composes all the pages. I am migrating code to Flutter 2.10 with a verygoodcli app using verygoodanalysis.

Here is the Composition root:

class CompositionRoot {
  static late SharedPreferences _sharedPreferences;
  static late ILocalStore _localStore;
  static late String _baseUrl;
  static late Client _client;

  static void configure() {
    _localStore = LocalStore(_sharedPreferences);
    _client = Client();
    _baseUrl = 'http://localhost:3000';
  }

  static Widget composeAuthUI() {
    final IAuthApi _api = AuthApi(_baseUrl, _client);
    final _manager = AuthManager(_api);
    final _authCubit = AuthstateCubit(_localStore);
    final _signUpService = SignUpService(_api);

    return BlocProvider(
      create: (BuildContext context) => _authCubit,
      child: AuthPage(_manager, _signUpService),
    );
  }
}

However when I run the code, I seem to get the following error message:

Error: LateInitializationError: Field 'sharedPreferences' has not been
initialized.
    at Object.throw_ [as throw] (http://localhost:40837/dart_sdk.js:5067:11)
    at Function.get sharedPreferences [as sharedPreferences]
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:58
    :37)
    at Function.configure
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:88
    :118)
    at main
    (http://localhost:40837/packages/verygoodapp/main_development.dart.lib.js:45
    :38)
    at main (http://localhost:40837/web_entrypoint.dart.lib.js:36:29)
    at main.next (<anonymous>)

How can I debug this errror also do you mind explaining whats going on, I can't seem to understand. The app is configured in the main_*.dart file before the UI is composed.

main_*.dart

void main() {
  CompositionRoot.configure();
  bootstrap(() => const App());
}

Our App Widget Class:

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)),
        colorScheme: ColorScheme.fromSwatch(
          accentColor: const Color.fromARGB(255, 190, 27, 27),
        ),
      ),
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      home: CompositionRoot.composeAuthUI(),
    );
  }
}

I can't seem to understand please help. Thanks in advance.

Body:
_sharedPreferences has not been initialized. Meaning it is storing none and you are trying to use it

Try this

_sharedPreferences = await SharedPreferences.getInstance();
_localStore = LocalStore(_sharedPreferences);

Then you are good to go