问:
Undefined properties when looping through API Data
I have a function that retrieves data from an API and returns a JSON format of information. I am trying to loop through it and retrieve parts of the data, however I get an type error saying "Cannot read properties of undefined (reading 'championId')"

```<code>
const { Title } = Typography;

const Homepage = () => {
  const [searchText, setSearchText] = useState("");
  const [playerData, setPlayerData] = useState({});
  const [playerStats, setPlayerStats] = useState({});
  const [champStats, setChampStats] = useState({});

  const API_KEY = "MYAPI";

  function searchForPlayer(event) {
    var APICallSummoner =
      "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" +
      searchText +
      "?api_key=" +
      API_KEY;

    axios
      .get(APICallSummoner)
      .then(function (response) {
        setPlayerData(response.data);
        if (response.data) {
          searchPlayerData(response.data.id);
          searchChampion(response.data.id);
          Rend();
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function searchChampion(id) {
    var API =
      "https://na1.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/" +
      id +
      "?api_key=" +
      API_KEY;

    axios
      .get(API)
      .then(function (response) {
        setChampStats(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function searchPlayerData(id) {
    var API =
      "https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/" +
      id +
      "?api_key=" +
      API_KEY;

    axios
      .get(API)
      .then(function (response) {
        setPlayerStats(response.data[1]);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function Rend() {
    const cham = [];
    console.log(championNames[champStats[0].championId]);
    for (var i = 0; i < 10; i++) {
      cham.push(championNames[champStats[i].championId]);
    }

    return <>{cham}</>;
  }

  // Total Games Played
  const total = playerStats.wins + playerStats.losses;
  const rank = playerStats.tier + " " + playerStats.rank;

  return (
    <>
      <Title level={2} className='heading'>
        LoLTracker
      </Title>
      <input
        type='text'
        onChange={(e) => setSearchText(e.target.value)}></input>
      <button
        onClick={(e) => {
          searchForPlayer(e);
        }}>
        Search Player
      </button>
      {JSON.stringify(playerData) != "{}" &&
      JSON.stringify(playerStats) != "{}" ? (
        <>
          <h1>{playerData.name}</h1>
          <img
            width='100'
            height='100'
            src={
              "http://ddragon.leagueoflegends.com/cdn/12.3.1/img/profileicon/" +
              playerData.profileIconId +
              ".png"
            }></img>
          <p>Summoner Level: {playerData.summonerLevel} </p>
          <Row>
            <Col span={12}>
              <Statistic title='Solo/Duo Games Played' value={total} />
            </Col>
            <Col span={12}>
              <Statistic title='Current Rank' value={rank} />
            </Col>
            <Col span={12}>
              <Statistic title='Solo/Duo Wins' value={playerStats.wins} />
            </Col>
            <Col span={12}>
              <Statistic title='Solo/Duo Losses' value={playerStats.losses} />
            </Col>
          </Row>
          <div className='home-heading-container'>
            <Title level={2} className='home-title'>
              Most Played Champions
            </Title>
          </div>

          <Rend />
        </>
      ) : (
        <>
          <h1>There is no data for this player, INACTIVE</h1>
        </>
      )}
    </>
  );
};
</code>```

It is in my Rend(), function. championNames is my own JSON file I created that retrieves the name of a character from its ID. How can I loop through the data to display what I want?

```<code>at Rend (Homepage.jsx:77:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)"
 Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    at Homepage (http://localhost:3000/static/js/bundle.js:243:86)
    at Routes (http://localhost:3000/static/js/bundle.js:61578:5)
    at div
    at section
    at BasicLayout (http://localhost:3000/static/js/bundle.js:6383:63)
    at Adapter (http://localhost:3000/static/js/bundle.js:6351:66)
    at div
    at div
    at App
    at Router (http://localhost:3000/static/js/bundle.js:61511:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:60991:5```

Thanks
```

答:
You are getting undefined for some champ. Try ignoring it somehow. Here is an example:

```<code>for (var i = 0; i < 10; i++) {

  champStats[i].championId ?
   cham.push(championNames[champStats[i].championId]) : null
}
</code>```

My theory is that some champ in the iteration from 0 to 10 does not exist.

Body:
I have a function that retrieves data from an API and returns a JSON format of information. I am trying to loop through it and retrieve parts of the data, however I get an type error saying "Cannot read properties of undefined (reading 'championId')"

const { Title } = Typography;

const Homepage = () => {
  const [searchText, setSearchText] = useState("");
  const [playerData, setPlayerData] = useState({});
  const [playerStats, setPlayerStats] = useState({});
  const [champStats, setChampStats] = useState({});

  const API_KEY = "MYAPI";

  function searchForPlayer(event) {
    var APICallSummoner =
      "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" +
      searchText +
      "?api_key=" +
      API_KEY;

    axios
      .get(APICallSummoner)
      .then(function (response) {
        setPlayerData(response.data);
        if (response.data) {
          searchPlayerData(response.data.id);
          searchChampion(response.data.id);
          Rend();
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function searchChampion(id) {
    var API =
      "https://na1.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/" +
      id +
      "?api_key=" +
      API_KEY;

    axios
      .get(API)
      .then(function (response) {
        setChampStats(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function searchPlayerData(id) {
    var API =
      "https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/" +
      id +
      "?api_key=" +
      API_KEY;

    axios
      .get(API)
      .then(function (response) {
        setPlayerStats(response.data[1]);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function Rend() {
    const cham = [];
    console.log(championNames[champStats[0].championId]);
    for (var i = 0; i < 10; i++) {
      cham.push(championNames[champStats[i].championId]);
    }

    return <>{cham}</>;
  }

  // Total Games Played
  const total = playerStats.wins + playerStats.losses;
  const rank = playerStats.tier + " " + playerStats.rank;

  return (
    <>
      <Title level={2} className='heading'>
        LoLTracker
      </Title>
      <input
        type='text'
        onChange={(e) => setSearchText(e.target.value)}></input>
      <button
        onClick={(e) => {
          searchForPlayer(e);
        }}>
        Search Player
      </button>
      {JSON.stringify(playerData) != "{}" &&
      JSON.stringify(playerStats) != "{}" ? (
        <>

{playerData.name}

Summoner Level: {playerData.summonerLevel}

          <Row>
            <Col span={12}>
              <Statistic title='Solo/Duo Games Played' value={total} />
            </Col>
            <Col span={12}>
              <Statistic title='Current Rank' value={rank} />
            </Col>
            <Col span={12}>
              <Statistic title='Solo/Duo Wins' value={playerStats.wins} />
            </Col>
            <Col span={12}>
              <Statistic title='Solo/Duo Losses' value={playerStats.losses} />
            </Col>
          </Row>

            <Title level={2} className='home-title'>
              Most Played Champions
            </Title>

          <Rend />
        </>
      ) : (
        <>

There is no data for this player, INACTIVE

        </>
      )}
    </>
  );
};

It is in my Rend(), function. championNames is my own JSON file I created that retrieves the name of a character from its ID. How can I loop through the data to display what I want?

at Rend (Homepage.jsx:77:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)"
 Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    at Homepage (http://localhost:3000/static/js/bundle.js:243:86)
    at Routes (http://localhost:3000/static/js/bundle.js:61578:5)
    at div
    at section
    at BasicLayout (http://localhost:3000/static/js/bundle.js:6383:63)
    at Adapter (http://localhost:3000/static/js/bundle.js:6351:66)
    at div
    at div
    at App
    at Router (http://localhost:3000/static/js/bundle.js:61511:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:60991:5```

Thanks

Body:
You are getting undefined for some champ. Try ignoring it somehow. Here is an example:

for (var i = 0; i < 10; i++) {

  champStats[i].championId ?
   cham.push(championNames[champStats[i].championId]) : null
}

My theory is that some champ in the iteration from 0 to 10 does not exist.


来源: stackexchange

问:
Efficient looping and comparing properties of two similar objects
I have a function find() that needs to loop through a lot of objects to identify a similar object by comparing a bunch of properties.

```<code>class Target:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class Source:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

def find(target: Target, source_set: set):
    for s in source_set:
        if s.a == target.a:
            if s.b == target.b:
                if s.c == target.c:
                    print("Found!")

source_set = {
    Source(a=1, b=2, c=3),
    Source(a=4, b=2, c=4)
}

target = Target(a=4, b=2, c=4)

find(target, source_set)
</code>```

The current function is very slow as my source_set can be millions.

The source_set creation and its Source objects can be adjusted (e.g. the type). The source_set itself is not modified after initialisation.

The Source objects creation's input is coming from a dict with the same properties. One Source's raw input data is like this:

```<code>{'a': '1', 'b': '2', 'c': '3'}
</code>```

The source_set is searched with many targets.

Is there a nice way to be more efficient? I'm hoping to not need to change the data structure.

答:
Since the source_set is only created once, but searched with many targets (as stated in your question), it is beneficial to invest time into creating a data structure for the source_set (which is only done once) if the reward is a time gain for the comparison later on (which is done multiple times).

Python's set provides the desired functionality. Internally it is somehow implemented as a hash map (not sure on this). To make use of the in statement, the elements in the set and also the elements that are compared to the set have to be hashable and comparable, i.e. both provide a __hash__ method and one of them provide a __eq__ method.

```<code>class Target:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __hash__(self):
        return hash((self.a, self.b, self.c))

class Source:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __eq__(self, other):
        return self.a == other.a and self.b == other.b and self.c == other.c

    def __hash__(self):
        return hash((self.a, self.b, self.c))
</code>```

Now building the set of Source elements is a time investment, because for each element that is added, the __hash__ method is applied.

```<code>source_set = {
    Source(a=1, b=2, c=3),
    Source(a=4, b=2, c=4),
}
</code>```

However, the reward is that now checking if a target is in the source_set happens in constant time compared to your current approach by comparing the target consecutively to each of the Sources which is in linear time.

```<code>target = Target(a=4, b=2, c=4)
target in source_set
# returns True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a function find() that needs to loop through a lot of objects to identify a similar object by comparing a bunch of properties.

class Target:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class Source:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

def find(target: Target, source_set: set):
    for s in source_set:
        if s.a == target.a:
            if s.b == target.b:
                if s.c == target.c:
                    print("Found!")

source_set = {
    Source(a=1, b=2, c=3),
    Source(a=4, b=2, c=4)
}

target = Target(a=4, b=2, c=4)

find(target, source_set)

The current function is very slow as my source_set can be millions.

The source_set creation and its Source objects can be adjusted (e.g. the type). The source_set itself is not modified after initialisation.

The Source objects creation's input is coming from a dict with the same properties. One Source's raw input data is like this:

{'a': '1', 'b': '2', 'c': '3'}

The source_set is searched with many targets.

Is there a nice way to be more efficient? I'm hoping to not need to change the data structure.

Body:
Since the source_set is only created once, but searched with many targets (as stated in your question), it is beneficial to invest time into creating a data structure for the source_set (which is only done once) if the reward is a time gain for the comparison later on (which is done multiple times).

Python's set provides the desired functionality. Internally it is somehow implemented as a hash map (not sure on this). To make use of the in statement, the elements in the set and also the elements that are compared to the set have to be hashable and comparable, i.e. both provide a __hash__ method and one of them provide a __eq__ method.

class Target:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __hash__(self):
        return hash((self.a, self.b, self.c))

class Source:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __eq__(self, other):
        return self.a == other.a and self.b == other.b and self.c == other.c

    def __hash__(self):
        return hash((self.a, self.b, self.c))

Now building the set of Source elements is a time investment, because for each element that is added, the __hash__ method is applied.

source_set = {
    Source(a=1, b=2, c=3),
    Source(a=4, b=2, c=4),
}

However, the reward is that now checking if a target is in the source_set happens in constant time compared to your current approach by comparing the target consecutively to each of the Sources which is in linear time.

target = Target(a=4, b=2, c=4)
target in source_set
# returns True


问:
Adding XML layout to custom ViewGroup at run-time - Android
Is it possible to add a XML layout to custom extended ViewGroup at runtime?

I tried adding the layout using LayoutInflator.inflate(...) method but it only returns the root node of the xml layout. Is there any way to inflate the full layout and add it to the ViewGroup?

Thanks

答:
You can insert a view at any position using the index argument of view.addView(). When you create a new instance of your ViewGroup, you should be able to call:

```<code>myCustomViewGroup.addView(View childView, int index, ViewGroup.LayoutParams params);
</code>```

To get your childView, use LayoutInflator (or findViewById(int))

```<code>View childView = layoutInflater.inflate(XmlResourceId, myCustomViewGroup);
</code>```

My syntax may not be exactly right but this should point you in the right direction.

ContentLicense: CC BY-SA 3.0

Body:
You can insert a view at any position using the index argument of view.addView(). When you create a new instance of your ViewGroup, you should be able to call:

myCustomViewGroup.addView(View childView, int index, ViewGroup.LayoutParams params);

To get your childView, use LayoutInflator (or findViewById(int))

View childView = layoutInflater.inflate(XmlResourceId, myCustomViewGroup);

My syntax may not be exactly right but this should point you in the right direction.


问:
Can you create an AWS CloudFormation stack on a t2.micro instance?
I am trying to do MongoDB on AWS following the AWS deployment guide. It is defaulted to boot up m5.large EC2s. However, I am only experimenting so I want to use a free tier EC2. When I add t2.micro to the allowed values and set it as default I get an error as pictured below.

Is there anyway I can get MongoDB running on AWS with 3 replications using the cloudformation method with free tier t2.micro instances.? If not, any better methods?

答:
The MongoDB on AWS - Quick Start has multiple templates that are deployed.

I notice that the NodeInstanceType is used and defined in multiple templates, presumably with the values passed from the master template to the node templates. Therefore, your changes will probably need to be made on any template that defines the NodeInstanceType parameter. I recommend you check all of the templates for such references.


问:
Node-JS - Express and child_process capturing output
I am wondering if there is a way for me to have an express server handle requests to a child_process process.

For example, I want to be able to send a command to for example cmd.exe, and get the response to emit to the client doing the request.

Thanks.

EDIT:

How I've tried it so far is:

Spawn the child_process via

```<code>var proc = spawn(config.cmd, config.args, { cwd: config.cwd });
</code>```

And then piping the output via:

```<code>proc.stdout.on('data', function(data) {res.send(data)});
</code>```

However, this doesn't actually return the data due to it returning the command that was sent. I was wondering if there was a promise function like:

```<code>proc.stdin.write("command").then
</code>```

This is a process that is not ending after the command, it will keep running. So I cannot just wait for all the responses.

Thanks.

答:
Run the server: npm app.js

```<code>// app.js
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const express = require('express');

const PORT = 10080;

const app = express();
app.use(async (req, res) => {
   const cmd = 'echo "Hello from terminal"'; //replace this line with your code.
   const dir = await exec(cmd);
   res.json(`hello from server + ${dir.stdout}`);
});

app.listen(PORT, () => console.log(`Listining on port:${PORT}`));
</code>```

curl http://localhost:10080

```<code>StatusCode        : 200
StatusDescription : OK
Content           : "hello from server + \"Hello from terminal\"\r\n"
Headers           : {[Connection, keep-alive], [Keep-Alive, timeout=5],
                    [Content-Length, 48], [Content-Type, application/json;
</code>```

Body:
I am wondering if there is a way for me to have an express server handle requests to a child_process process.

For example, I want to be able to send a command to for example cmd.exe, and get the response to emit to the client doing the request.

Thanks.

EDIT:

How I've tried it so far is:

Spawn the child_process via

var proc = spawn(config.cmd, config.args, { cwd: config.cwd });

And then piping the output via:

proc.stdout.on('data', function(data) {res.send(data)});

However, this doesn't actually return the data due to it returning the command that was sent. I was wondering if there was a promise function like:

proc.stdin.write("command").then

This is a process that is not ending after the command, it will keep running. So I cannot just wait for all the responses.

Thanks.

Body:
Run the server: npm app.js

// app.js
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const express = require('express');

const PORT = 10080;

const app = express();
app.use(async (req, res) => {
   const cmd = 'echo "Hello from terminal"'; //replace this line with your code.
   const dir = await exec(cmd);
   res.json(`hello from server + ${dir.stdout}`);
});

app.listen(PORT, () => console.log(`Listining on port:${PORT}`));

curl http://localhost:10080

StatusCode        : 200
StatusDescription : OK
Content           : "hello from server + \"Hello from terminal\"\r\n"
Headers           : {[Connection, keep-alive], [Keep-Alive, timeout=5],
                    [Content-Length, 48], [Content-Type, application/json;


问:
Unknown Coder URN beam:coder:pickled_python:v1 when running beam with a custom expansion service
I've got an Apache Beam pipeline that uses Java only firestore transforms in a python pipeline with the help of an expansion service that exposes the firestore read transforms.

Here I am trying to list all my documents in the collection named pokemon

This is my python pipeline:

def run():
      """Main function that defines pipeline and runs it."""
      pipeline_options = get_pipeline_options(**vars(args))

      request = ListDocumentsRequest()
      request.parent = 'projects/PROJECT_ID/databases'
      request.collection_id = 'pokemon'

      with beam.Pipeline(options=pipeline_options) as pipeline:
        _ = (pipeline
            | 'Create Requests' >> beam.Create([request.transaction])
                .with_output_types(typing.List[bytes])
            | 'Read from JavaFirestore' >> beam.ExternalTransform(
                'my.beam.transform.firestore_list_documents',
                ImplicitSchemaPayloadBuilder({'parent': request.parent,
                                            'collectionId': request.collection_id}),
                "localhost:12345")
            | 'Write' >> WriteToText('output_files/output')
            )
```
<p>This is the Java code that exposes the transform/URN in the expansion service:</p>
<pre class="lang-java prettyprint-override"><code>public static class FirestoreListDocumentsBuilder implements
      ExternalTransformBuilder<FirestoreTransformsConfiguration, PCollection<ListDocumentsRequest>, PCollection<Document>> {

    @Override
    public PTransform<PCollection<ListDocumentsRequest>, PCollection<Document>> buildExternal(
      FirestoreTransformsConfiguration configuration) {
      return FirestoreIO.v1().read().listDocuments().build();
    }
  }

@AutoService(ExternalTransformRegistrar.class)
public class FirestoreTransformsRegistrar implements ExternalTransformRegistrar {

  final static String URN_LIST_DOCS = "my.beam.transform.firestore_list_documents";

  @Override
  public Map<String, ExternalTransformBuilder<?, ?, ?>> knownBuilderInstances() {
    return ImmutableMap.of(
      URN_LIST_DOCS,new FirestoreListDocumentsBuilder()
    );
  }
}
</code>```

But I am getting the following error when running the python pipeline this:

```<code>java.lang.IllegalArgumentException: Unknown Coder URN beam:coder:pickled_python:v1. Known URNs: [beam:coder:avro:generic:v1, beam:coder:bytes:v1, beam:coder:bool:v1, beam:coder:string_utf8:v1, beam:coder:kv:v1, beam:coder:varint:v1, beam:coder:interval_window:v1, beam:coder:iterable:v1, beam:coder:timer:v1, beam:coder:length_prefix:v1, beam:coder:global_window:v1, beam:coder:windowed_value:v1, beam:coder:param_windowed_value:v1, beam:coder:double:v1, beam:coder:row:v1, beam:coder:sharded_key:v1, beam:coder:custom_window:v1]
</code>```

I am struggling to find the solution to this problem, anyone that could help me out?

答: This is because (surprisingly) List is not a "standard" cross-language coder. Try using with_output_types(typing.Iterable[bytes]) instead. (Your java code will have to change to take a PCollection of Iterable<byte[]> to match.)

Body:
I've got an Apache Beam pipeline that uses Java only firestore transforms in a python pipeline with the help of an expansion service that exposes the firestore read transforms.

Here I am trying to list all my documents in the collection named pokemon

This is my python pipeline:

def run():
      """Main function that defines pipeline and runs it."""
      pipeline_options = get_pipeline_options(**vars(args))

      request = ListDocumentsRequest()
      request.parent = 'projects/PROJECT_ID/databases'
      request.collection_id = 'pokemon'

      with beam.Pipeline(options=pipeline_options) as pipeline:
        _ = (pipeline
            | 'Create Requests' >> beam.Create([request.transaction])
                .with_output_types(typing.List[bytes])
            | 'Read from JavaFirestore' >> beam.ExternalTransform(
                'my.beam.transform.firestore_list_documents',
                ImplicitSchemaPayloadBuilder({'parent': request.parent,
                                            'collectionId': request.collection_id}),
                "localhost:12345")
            | 'Write' >> WriteToText('output_files/output')
            )

This is the Java code that exposes the transform/URN in the expansion service:

public static class FirestoreListDocumentsBuilder implements
      ExternalTransformBuilder<FirestoreTransformsConfiguration, PCollection<ListDocumentsRequest>, PCollection<Document>> {

    @Override
    public PTransform<PCollection<ListDocumentsRequest>, PCollection<Document>> buildExternal(
      FirestoreTransformsConfiguration configuration) {
      return FirestoreIO.v1().read().listDocuments().build();
    }
  }

@AutoService(ExternalTransformRegistrar.class)
public class FirestoreTransformsRegistrar implements ExternalTransformRegistrar {

  final static String URN_LIST_DOCS = "my.beam.transform.firestore_list_documents";

  @Override
  public Map<String, ExternalTransformBuilder<?, ?, ?>> knownBuilderInstances() {
    return ImmutableMap.of(
      URN_LIST_DOCS,new FirestoreListDocumentsBuilder()
    );
  }
}

But I am getting the following error when running the python pipeline this:

java.lang.IllegalArgumentException: Unknown Coder URN beam:coder:pickled_python:v1. Known URNs: [beam:coder:avro:generic:v1, beam:coder:bytes:v1, beam:coder:bool:v1, beam:coder:string_utf8:v1, beam:coder:kv:v1, beam:coder:varint:v1, beam:coder:interval_window:v1, beam:coder:iterable:v1, beam:coder:timer:v1, beam:coder:length_prefix:v1, beam:coder:global_window:v1, beam:coder:windowed_value:v1, beam:coder:param_windowed_value:v1, beam:coder:double:v1, beam:coder:row:v1, beam:coder:sharded_key:v1, beam:coder:custom_window:v1]

I am struggling to find the solution to this problem, anyone that could help me out?


问:
Querying JSONB fields with joins
I have a database with two tables. One containing events & the other containing attendees for those events. Theses events have a jsonb field containing an array of objects with a "duration" attribute

events

id
name
occurrences

1
"The Great Beyond"
[{"duration": 100}, {"duration": 200}, {"duration": 300}]

2
"The Final Countdown"
[{"duration": 50}]

3
"The Next Plain"
null

attendees

id
name
event_id

1
"Bob"
1

2
"Susan"
2

3
"Terry"
3

I want to run a single query to pull data about these events & showcase the name of the event, how many people are attending & what the current "duration" is for each event (by summing up all the duration values in the occurrences column.

The current query I use is resulting in incorrect COUNT values for my attendees. I suspect it has to do with the way I am constructing my JOINs such that additional rows are being created.

SELECT
  events.id AS "ID",
  events.name AS "Name",
  SUM(coalesce(occurrences_arry->'duration', '0'):int) as "Duration",
  COUNT(attendees.*) as "Attendees"
FROM
  events
    INNER JOIN attendees on attendees.event_id = events.id
    LEFT JOIN jsonb_array_elements(events.occurrences) as occurrences_arry on true
GROUP BY events.id
```

The result I get back has too high of a count for "Attendees" (The last record should have 1 attendees but says 3). I am pretty sure it has to do with the INNER JOIN LEFT JOIN combo I am using so that I can utilize jsonb_array_elements. Every time a new occurrence is added the attendees count grows

ID
Name
Duration
Attendees

2
"The Final Countdown"
50
1

3
"The Next Plain"
0
1

1
"The Great Beyond"
600
3

How can I best perform an INNER JOIN on my attendees table and ALSO sum up all the durations in for each event?

答:
You can count the duration in a subquery. You have most of the code that is needed already, you just have to move it, example:

```<code>SELECT
  events.id AS "ID",
  events.name AS "Name",
  (SELECT coalesce(SUM((occurrences_arry->>'duration')::int), 0)
   FROM jsonb_array_elements(events.occurrences) as occurrences_arry) as "Duration",
  COUNT(attendees.*) as "Attendees"
FROM
  events
    INNER JOIN attendees on attendees.event_id = events.id
GROUP BY events.id
</code>```

A SUM returns null, if there are no rows, hence I used coalesce to default to 0 in this case.

Title: Querying JSONB fields with joins

Body:
I have a database with two tables. One containing events & the other containing attendees for those events. Theses events have a jsonb field containing an array of objects with a "duration" attribute

events

id
name
occurrences

1
"The Great Beyond"
[{"duration": 100}, {"duration": 200}, {"duration": 300}]

2
"The Final Countdown"
[{"duration": 50}]

3
"The Next Plain"
null

attendees

id
name
event_id

1
"Bob"
1

2
"Susan"
2

3
"Terry"
3

I want to run a single query to pull data about these events & showcase the name of the event, how many people are attending & what the current "duration" is for each event (by summing up all the duration values in the occurrences column.

The current query I use is resulting in incorrect COUNT values for my attendees. I suspect it has to do with the way I am constructing my JOINs such that additional rows are being created.

SELECT
  events.id AS "ID",
  events.name AS "Name",
  SUM(coalesce(occurrences_arry->'duration', '0'):int) as "Duration",
  COUNT(attendees.*) as "Attendees"
FROM
  events
    INNER JOIN attendees on attendees.event_id = events.id
    LEFT JOIN jsonb_array_elements(events.occurrences) as occurrences_arry on true
GROUP BY events.id

The result I get back has too high of a count for "Attendees" (The last record should have 1 attendees but says 3). I am pretty sure it has to do with the INNER JOIN LEFT JOIN combo I am using so that I can utilize jsonb_array_elements. Every time a new occurrence is added the attendees count grows

ID
Name
Duration
Attendees

2
"The Final Countdown"
50
1

3
"The Next Plain"
0
1

1
"The Great Beyond"
600
3

How can I best perform an INNER JOIN on my attendees table and ALSO sum up all the durations in for each event?

Body:
You can count the duration in a subquery. You have most of the code that is needed already, you just have to move it, example:

SELECT
  events.id AS "ID",
  events.name AS "Name",
  (SELECT coalesce(SUM((occurrences_arry->>'duration')::int), 0)
   FROM jsonb_array_elements(events.occurrences) as occurrences_arry) as "Duration",
  COUNT(attendees.*) as "Attendees"
FROM
  events
    INNER JOIN attendees on attendees.event_id = events.id
GROUP BY events.id

A SUM returns null, if there are no rows, hence I used coalesce to default to 0 in this case.


问:
MIN and MAX of dates producing wrong output
I have Payment Data and I want to show MIN and MAX dates based on different Payment Types and COUNT number of payments and adjustments.

```<code>CREATE TABLE Payment
(BillingId int, PaymentId int, PaymentDate date, PaymentType varchar(50), PaymentBy varchar(50));

INSERT INTO Payment
VALUES
(12345, 1, '2022-02-02', 'payment', 'Insurance'),
(12345, 2, '2022-02-02', 'adjustment', 'Insurance'),
(67890, 3, '2022-01-19', 'payment', 'Insurance'),
(67890, 4, '2022-01-19', 'adjustment', 'Insurance'),
(67890, 5, '2022-01-19', 'payment', 'Insurance'),
(67890, 6, '2022-02-02', 'payment', 'Client')

SELECT * FROM Payment
</code>```

BillingId
PaymentId
PaymentDate
PaymentType
PaymentBy

12345
1
2022-02-02
payment
Insurance

12345
2
2022-02-02
adjustment
Insurance

67890
3
2022-01-19
payment
Insurance

67890
4
2022-01-19
adjustment
Insurance

67890
5
2022-01-19
payment
Insurance

67890
6
2022-02-02
payment
Client

I need to GROUP data BY BillingId and show 6 dates (issue in them, specifically in MIN) and 4 total counts (they produce correct output):

MIN date when Insurance made payment

MAX date when Insurance made payment

MIN date when Client made payment

MAX date when Client made payment

MIN date when Adjustment was made

MAX date when Adjustment was made

COUNT of all payments (without adjustments)

COUNT amount of payments made by Insurance

COUNT amount of payments made by Client

COUNT amount of adjustments

P.S. If only 1 payment was made by Insurance, for example, then MIN and MAX dates should be the same.

My code:

```<code>SELECT p.BillingId,

        MIN(CASE WHEN p.PaymentBy = 'Insurance' AND p.PaymentType != 'adjustment' THEN p.PaymentDate ELSE '' END) AS EarliestDateInsurancePaid,
        MAX(CASE WHEN p.PaymentBy = 'Insurance' AND p.PaymentType != 'adjustment'  THEN p.PaymentDate ELSE '' END) AS LatestDateInsurancePaid,
        MIN(CASE WHEN p.PaymentBy = 'Client' AND p.PaymentType != 'adjustment' THEN p.PaymentDate ELSE '' END) AS EarliestDateClientPaid,
        MAX(CASE WHEN p.PaymentBy = 'Client' AND p.PaymentType != 'adjustment' THEN p.PaymentDate ELSE '' END) AS LatestDateClientPaid,
        MIN(CASE WHEN p.PaymentType = 'adjustment' THEN p.PaymentDate ELSE '' END) AS EarliestAdjustmentDate,
        MAX(CASE WHEN p.PaymentType = 'adjustment' THEN p.PaymentDate ELSE '' END) AS LatestAdjustmentDate,

        COUNT(CASE WHEN p.PaymentType != 'adjustment' THEN p.PaymentType END) AS TotalAmountOfPayments,
        COUNT(CASE WHEN p.PaymentBy = 'Insurance' AND p.PaymentType != 'adjustment' THEN p.PaymentBy END) AS AmountOfInsurancePayments,
        COUNT(CASE WHEN p.PaymentBy = 'Client' AND p.PaymentType != 'adjustment' THEN p.PaymentBy END) AS AmountOfClientPayments,
        COUNT(CASE WHEN p.PaymentType = 'adjustment' THEN p.PaymentType END) AS AmountOfAdjustments

FROM Payment AS p
GROUP BY p.BillingId
</code>```

Output from the above query:

BillingId
EarliestDateInsurancePaid
LatestDateInsurancePaid
EarliestDateClientPaid
LatestDateClientPaid
EarliestAdjustmentDate
LatestAdjustmentDate
TotalAmountOfPayments
AmountOfInsurancePayments
AmountOfClientPayments
AmountOfAdjustments

12345
1900-01-01
2022-02-02
1900-01-01
1900-01-01
1900-01-01
2022-02-02
1
1
0
1

67890
1900-01-01
2022-01-19
1900-01-01
2022-02-02
1900-01-01
2022-01-19
3
2
1
1

Output I need:

BillingId
EarliestDateInsurancePaid
LatestDateInsurancePaid
EarliestDateClientPaid
LatestDateClientPaid
EarliestAdjustmentDate
LatestAdjustmentDate
TotalAmountOfPayments
AmountOfInsurancePayments
AmountOfClientPayments
AmountOfAdjustments

12345
2022-02-02
2022-02-02
1900-01-01
1900-01-01
2022-02-02
2022-02-02
1
1
0
1

67890
2022-01-19
2022-01-19
2022-02-02
2022-02-02
2022-01-19
2022-01-19
3
2
1
1

答: Your use of max(case when..else '' end... is causing the 1900 date, because the max function does not ignore empty/zero length strings, they are converted to date. Use NULL (or no ELSE part, defaults to NULL); MAX and many other aggregate functions ignore NULL values.

Body:
I have Payment Data and I want to show MIN and MAX dates based on different Payment Types and COUNT number of payments and adjustments.

CREATE TABLE Payment
(BillingId int, PaymentId int, PaymentDate date, PaymentType varchar(50), PaymentBy varchar(50));

INSERT INTO Payment
VALUES
(12345, 1, '2022-02-02', 'payment', 'Insurance'),
(12345, 2, '2022-02-02', 'adjustment', 'Insurance'),
(67890, 3, '2022-01-19', 'payment', 'Insurance'),
(67890, 4, '2022-01-19', 'adjustment', 'Insurance'),
(67890, 5, '2022-01-19', 'payment', 'Insurance'),
(67890, 6, '2022-02-02', 'payment', 'Client')

SELECT * FROM Payment

BillingId
PaymentId
PaymentDate
PaymentType
PaymentBy

12345
1
2022-02-02
payment
Insurance

12345
2
2022-02-02
adjustment
Insurance

67890
3
2022-01-19
payment
Insurance

67890
4
2022-01-19
adjustment
Insurance

67890
5
2022-01-19
payment
Insurance

67890
6
2022-02-02
payment
Client

I need to GROUP data BY BillingId and show 6 dates (issue in them, specifically in MIN) and 4 total counts (they produce correct output):

MIN date when Insurance made payment

MAX date when Insurance made payment

MIN date when Client made payment

MAX date when Client made payment

MIN date when Adjustment was made

MAX date when Adjustment was made

COUNT of all payments (without adjustments)

COUNT amount of payments made by Insurance

COUNT amount of payments made by Client

COUNT amount of adjustments

P.S. If only 1 payment was made by Insurance, for example, then MIN and MAX dates should be the same.

My code:

SELECT p.BillingId,

        MIN(CASE WHEN p.PaymentBy = 'Insurance' AND p.PaymentType != 'adjustment' THEN p.PaymentDate ELSE '' END) AS EarliestDateInsurancePaid,
        MAX(CASE WHEN p.PaymentBy = 'Insurance' AND p.PaymentType != 'adjustment'  THEN p.PaymentDate ELSE '' END) AS LatestDateInsurancePaid,
        MIN(CASE WHEN p.PaymentBy = 'Client' AND p.PaymentType != 'adjustment' THEN p.PaymentDate ELSE '' END) AS EarliestDateClientPaid,
        MAX(CASE WHEN p.PaymentBy = 'Client' AND p.PaymentType != 'adjustment' THEN p.PaymentDate ELSE '' END) AS LatestDateClientPaid,
        MIN(CASE WHEN p.PaymentType = 'adjustment' THEN p.PaymentDate ELSE '' END) AS EarliestAdjustmentDate,
        MAX(CASE WHEN p.PaymentType = 'adjustment' THEN p.PaymentDate ELSE '' END) AS LatestAdjustmentDate,

        COUNT(CASE WHEN p.PaymentType != 'adjustment' THEN p.PaymentType END) AS TotalAmountOfPayments,
        COUNT(CASE WHEN p.PaymentBy = 'Insurance' AND p.PaymentType != 'adjustment' THEN p.PaymentBy END) AS AmountOfInsurancePayments,
        COUNT(CASE WHEN p.PaymentBy = 'Client' AND p.PaymentType != 'adjustment' THEN p.PaymentBy END) AS AmountOfClientPayments,
        COUNT(CASE WHEN p.PaymentType = 'adjustment' THEN p.PaymentType END) AS AmountOfAdjustments

FROM Payment AS p
GROUP BY p.BillingId

Output from the above query:

BillingId
EarliestDateInsurancePaid
LatestDateInsurancePaid
EarliestDateClientPaid
LatestDateClientPaid
EarliestAdjustmentDate
LatestAdjustmentDate
TotalAmountOfPayments
AmountOfInsurancePayments
AmountOfClientPayments
AmountOfAdjustments

12345
1900-01-01
2022-02-02
1900-01-01
1900-01-01
1900-01-01
2022-02-02
1
1
0
1

67890
1900-01-01
2022-01-19
1900-01-01
2022-02-02
1900-01-01
2022-01-19
3
2
1
1

Output I need:

BillingId
EarliestDateInsurancePaid
LatestDateInsurancePaid
EarliestDateClientPaid
LatestDateClientPaid
EarliestAdjustmentDate
LatestAdjustmentDate
TotalAmountOfPayments
AmountOfInsurancePayments
AmountOfClientPayments
AmountOfAdjustments

12345
2022-02-02
2022-02-02
1900-01-01
1900-01-01
2022-02-02
2022-02-02
1
1
0
1

67890
2022-01-19
2022-01-19
2022-02-02
2022-02-02
2022-01-19
2022-01-19
3
2
1
1


问:
QImage/QPixmap size limitations?
Are there any known size/space limitation of QPixmap and/or QImage objects documented? I did not find any useful information regarding this. I'm currently using Qt 4.7.3 on OSX and Windows. Particulary I'm interested in:

Width/Height limits?

Limits depending on color format?

Difference between 32/64 bit machines?

Difference regarding OS?

I would naively suspect that memory is the only limitation, so one could calculate max size by

width x height x byte_per_pixel

I assume that there is a more elaborate rule of thumb; also 32 bit machines may have addressing problems when you run into GB dimensions.

In the end I want to store multiple RGBA images of about 16000x16000 pixel in size and render them using transparency onto each other within a QGraphicsScene. The workstation available can have a lot of RAM, let's say 16GB.

tl;dr: What size limits of QImage/QPixmap are you aware of, or where can I find such information?

Edit: I'm aware of the tiling approach and I'm fine with that. Still it would be great to know the things described above.

Thanks!

答:
Are you building a 64 bit app? If not, you are going to run into memory issues very quickly. On Windows, even if the machine has 16GB ram, a 32 bit process will be limited to 2GB (Unless it is LARGEADDRESSAWARE then 3GB). A 16000x16000 image will be just under 1 GB, so you'll only be able to allocate enough memory for 1, maybe 2 if you are very lucky.

With a 64 bit app you should be able to allocate enough memory for several images.

Title: QImage/QPixmap size limitations?


问:
Dealing with Safari and .webp images in 2022
I've been waiting to use .webp images for a very long time.

It's 2022, so, given:

the image format has existed for a decade

Chrome started supporting .webp in Jan 2014

Firefox started supporting .webp in Jan 2019

I decided the day before yesterday to take the plunge and convert a bunch of .png images on a website to .webp images.

Rookie error. Because, of course, I should have checked: https://caniuse.com/webp first and that would have told me that Safari on anything earlier than macOS 11.0 Big Sur (Nov 2020) does not support .webp images.

But I'm tired of waiting. So... Safari can carry on using .png images I suppose.

Because I absolutely do want to serve .webp images to Firefox, Brave, Chrome, Edge, Opera etc. users.

If I were using marked up images, declaring one or more fallback images is elementary:

```<code><picture>
  <source srcset="a-webp-for-most-browsers.webp" type="image/webp">
  <source srcset="a-png-for-safari.png" type="image/png">
  <img src="a-png-for-safari.png" alt="My Image">
</picture>
</code>```

But (sigh) in this instance, the images are CSS background images, so options for creating fallbacks are more limited:

CSS image-set still has pretty low support at present

CSS feature queries using @supports do not extend to image formats.

Am I limited to browser-sniffing via PHP, like this:

```<code>if (preg_match('/Mac OS X/', $_SERVER['HTTP_USER_AGENT'])) {

  $Body_Element_CSS_Class_List .= ' oh-no-here-comes-safari';
}
</code>```

Is there a better / more reliable approach I can adopt than browser-detection?

答:
Yes, it's hard to provide fallbacks for CSS background-images

In my question I wrote:

If I were using marked-up images, declaring one or more fallback images is elementary [...]

But (sigh) in this instance, the images are CSS background-images, so options for creating fallbacks are more limited

And for now, at least, - ie. while we're still waiting (in 2022) for widespread cross-browser support for the CSS image-set() function - that's true.

But a marked-up  can replace each CSS background-image

While I was hunting around for alternative approaches, I unexpectedly came across this July 2021  comment by Quentin Albert:

For what most people use background images for you can nowadays easily use object-fit + object-position.

Source: https://css-tricks.com/using-performant-next-gen-images-in-css-with-image-set/

This was news to me. I was dimly aware of the object-fit CSS property, but I'd never come across the object-position CSS property at all.

But it absolutely works!!

The CSS I would have used if image-set() had support

If image-set() had extensive cross-browser support, this was my intended CSS, which would enable a fallback image for Safari:

```<code>.my-image-1 {
  background-image: url(image-set('my-sprited-images.webp', 'my-sprited-images.png'));
  background-position: 0, 0;
}

.my-image-2 {
  background-image: url(image-set('my-sprited-images.webp', 'my-sprited-images.png'));
  background-position: -100px, 0;
}
</code>```

The HTML + CSS I can use instead (thanks to object-position)

Since the above isn't close to reliable, I can declare the fallback image in HTML instead and position it using object-position:

HTML:

```<code><picture>
  <source srcset="my-sprited-images.webp" type="image/webp">
  <source srcset="my-sprited-images.png" type="image/png">
  <img class="my-image-1" src="/my-sprited-images.png" alt="My Image 1">
</picture>

<picture>
  <source srcset="my-sprited-images.webp" type="image/webp">
  <source srcset="my-sprited-images.png" type="image/png">
  <img class="my-image-2" src="/my-sprited-images.png" alt="My Image 2">
</picture>
</code>```

CSS:

```<code>.my-image-1 {
  object-position: 0 0;
}

.my-image-2 {
  object-position: -100px 0;
}
</code>```

Body:
I've been waiting to use .webp images for a very long time.

It's 2022, so, given:

the image format has existed for a decade

Chrome started supporting .webp in Jan 2014

Firefox started supporting .webp in Jan 2019

I decided the day before yesterday to take the plunge and convert a bunch of .png images on a website to .webp images.

Rookie error. Because, of course, I should have checked: https://caniuse.com/webp first and that would have told me that Safari on anything earlier than macOS 11.0 Big Sur (Nov 2020) does not support .webp images.

But I'm tired of waiting. So... Safari can carry on using .png images I suppose.

Because I absolutely do want to serve .webp images to Firefox, Brave, Chrome, Edge, Opera etc. users.

If I were using marked up images, declaring one or more fallback images is elementary:

<picture>
  <source srcset="a-webp-for-most-browsers.webp" type="image/webp">
  <source srcset="a-png-for-safari.png" type="image/png">

</picture>

But (sigh) in this instance, the images are CSS background images, so options for creating fallbacks are more limited:

CSS image-set still has pretty low support at present

CSS feature queries using @supports do not extend to image formats.

Am I limited to browser-sniffing via PHP, like this:

if (preg_match('/Mac OS X/', $_SERVER['HTTP_USER_AGENT'])) {

  $Body_Element_CSS_Class_List .= ' oh-no-here-comes-safari';
}

Is there a better / more reliable approach I can adopt than browser-detection?

Body:
Yes, it's hard to provide fallbacks for CSS background-images

In my question I wrote:

If I were using marked-up images, declaring one or more fallback images is elementary [...]

But (sigh) in this instance, the images are CSS background-images, so options for creating fallbacks are more limited

And for now, at least, - ie. while we're still waiting (in 2022) for widespread cross-browser support for the CSS image-set() function - that's true.

But a marked-up <img> can replace each CSS background-image

While I was hunting around for alternative approaches, I unexpectedly came across this July 2021  comment by Quentin Albert:

For what most people use background images for you can nowadays easily use object-fit + object-position.

Source: https://css-tricks.com/using-performant-next-gen-images-in-css-with-image-set/

This was news to me. I was dimly aware of the object-fit CSS property, but I'd never come across the object-position CSS property at all.

But it absolutely works!!

The CSS I would have used if image-set() had support

If image-set() had extensive cross-browser support, this was my intended CSS, which would enable a fallback image for Safari:

.my-image-1 {
  background-image: url(image-set('my-sprited-images.webp', 'my-sprited-images.png'));
  background-position: 0, 0;
}

.my-image-2 {
  background-image: url(image-set('my-sprited-images.webp', 'my-sprited-images.png'));
  background-position: -100px, 0;
}

The HTML + CSS I can use instead (thanks to object-position)

Since the above isn't close to reliable, I can declare the fallback image in HTML instead and position it using object-position:

HTML:

<picture>
  <source srcset="my-sprited-images.webp" type="image/webp">
  <source srcset="my-sprited-images.png" type="image/png">
  <img class="my-image-1" src="/my-sprited-images.png" alt="My Image 1">
</picture>

<picture>
  <source srcset="my-sprited-images.webp" type="image/webp">
  <source srcset="my-sprited-images.png" type="image/png">
  <img class="my-image-2" src="/my-sprited-images.png" alt="My Image 2">
</picture>

CSS:

.my-image-1 {
  object-position: 0 0;
}

.my-image-2 {
  object-position: -100px 0;
}


问:
Pressing a button to add an element to an array in LabVIEW
Is it possible to add an element to an array by pressing a button?
In such a way that the first press enters a '1' element, the second a '2' and so on.</p>

答:
Given how LabVIEW works, your question is borderline nonsensical. I'm going to try to untangle a few concepts that you seem to have conflated. I hope this doesn't come off as insulting -- I see genuine confusion and I'm hoping I can help.

First of all, what do you mean by "an array"? Do you mean the value on a wire or the value you see in a control on the front panel? LabVIEW's front panels are just the display of values computed in the block diagrams. In a running program, you never directly manipulate the values in any control. You can read the value, manipulate it, and then write it back to the control.

So, on the block diagram, yes, you can add an element to an array by using the "Build Array" node. And then you could display that value in an array indicator on the front panel.

You can have a button on the front panel that triggers an event. If that event code adds to an array, then you display that value in an indicator, then, yes, you can have a button that adds an element to an array. The code would look something like the code below. Notice that I never "add" an element to the array indicator. The array indicator simply updates every time the loop runs with whatever the computed value happens to be.

PS: the other frame of the event structure is just a "Stop" button handler.


问:
Widget not updating its colorScheme with global ThemeData
The app app here loads a tabbed simple app with a scaffold, app bar, and bottomNavigationBar which is set as a TabBar.

When set at the bottomNavigationBar, the TabBar becomes white so I've overridden its background color using a Container widget.

While the rest of my app will change its color palette as expected, however it doesn't for my TabBar. Using Theme.of(context) to get the primary color doesn't work either, as the Theme's color scheme doesn't seem to change at all.

I've attached pictures of the problem too.

theme: ThemeData.light()

theme: ThemeData.dark()

Notice how the whole app except the bottom TabBar reflects these changes happily.

```<code>void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Sereal',
        theme: ThemeData(primarySwatch: Colors.indigo),
        home: DefaultTabController(
          length: 3,
          child: Scaffold(
              appBar: AppBar(
                title: const Text('App'),
              ),
              bottomNavigationBar: Container(
                color: Theme.of(context).primaryColor,
                child: const TabBar(
                  tabs: <Widget>[
                    Tab(
                      icon: Icon(Icons.calendar_today),
                      text: 'Planner',
                    ),
                    Tab(
                      icon: Icon(Icons.amp_stories),
                      text: 'Cards',
                    ),
                    Tab(
                      icon: Icon(Icons.auto_stories),
                      text: 'Notes',
                    ),
                  ],
                ),
              ),
              body: const TabBarView(
                children: <Widget>[CardsView(), NotesView(), PlannerView()],
              )),
        ));
  }
}
</code>```

答:
1: make the DefaultTabController in a separate widget.

2: add these properties to the MaterialApp widget:

```<code>theme: ThemeData(
    brightness: Brightness.light,
    primarySwatch: Colors.indigo,
  ),
  darkTheme: ThemeData(
    brightness: Brightness.dark,
    primarySwatch: Colors.indigo,
  ),
  themeMode: ThemeMode.light,
</code>```

3: instead of wraping the TabBar with a Container, wrap it with a Material widget

this is the main file code :

```<code>   void main() {
    runApp(const MyApp());
  }

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

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Flutter Demo',
     theme: ThemeData(
       brightness: Brightness.light,
       primarySwatch: Colors.indigo,
     ),
     darkTheme: ThemeData(
       brightness: Brightness.dark,
       primarySwatch: Colors.indigo,
     ),
     themeMode: ThemeMode.light,
     home:  const HomePage(),
   );
 }
}
</code>```

this is the homepage code:

```<code>   import 'package:flutter/material.dart';

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

     @override
     Widget build(BuildContext context) {
       return  DefaultTabController(
             length: 3,
             child: Scaffold(
                 appBar: AppBar(
                   title: const Text('App'),
                 ),
                 bottomNavigationBar:  Material(
                     color : Theme.of(context).primaryColor,
                   child: TabBar(
                     tabs: <Widget>[
                       Tab(
                         icon: Icon(Icons.calendar_today),
                         text: 'Planner',
                       ),
                       Tab(
                         icon: Icon(Icons.amp_stories),
                         text: 'Cards',
                       ),
                       Tab(
                         icon: Icon(Icons.auto_stories),
                         text: 'Notes',
                       ),
                     ],
                   ),
                 ),
                 body: const TabBarView(
                   children: <Widget>[CardsView(), NotesView(),PlannerView()],
                 )),
           );
     }
   }
</code>```

.................

this is how it looks when you run the app:

and this is how it looks when you change the themeMode to: ThemeMode.dark

Body:
The app app here loads a tabbed simple app with a scaffold, app bar, and bottomNavigationBar which is set as a TabBar.

When set at the bottomNavigationBar, the TabBar becomes white so I've overridden its background color using a Container widget.

While the rest of my app will change its color palette as expected, however it doesn't for my TabBar. Using Theme.of(context) to get the primary color doesn't work either, as the Theme's color scheme doesn't seem to change at all.

I've attached pictures of the problem too.

theme: ThemeData.light()

theme: ThemeData.dark()

Notice how the whole app except the bottom TabBar reflects these changes happily.

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Sereal',
        theme: ThemeData(primarySwatch: Colors.indigo),
        home: DefaultTabController(
          length: 3,
          child: Scaffold(
              appBar: AppBar(
                title: const Text('App'),
              ),
              bottomNavigationBar: Container(
                color: Theme.of(context).primaryColor,
                child: const TabBar(
                  tabs: <Widget>[
                    Tab(
                      icon: Icon(Icons.calendar_today),
                      text: 'Planner',
                    ),
                    Tab(
                      icon: Icon(Icons.amp_stories),
                      text: 'Cards',
                    ),
                    Tab(
                      icon: Icon(Icons.auto_stories),
                      text: 'Notes',
                    ),
                  ],
                ),
              ),
              body: const TabBarView(
                children: <Widget>[CardsView(), NotesView(), PlannerView()],
              )),
        ));
  }
}

Body:
1: make the DefaultTabController in a separate widget.

2: add these properties to the MaterialApp widget:

theme: ThemeData(
    brightness: Brightness.light,
    primarySwatch: Colors.indigo,
  ),
  darkTheme: ThemeData(
    brightness: Brightness.dark,
    primarySwatch: Colors.indigo,
  ),
  themeMode: ThemeMode.light,

3: instead of wraping the TabBar with a Container, wrap it with a Material widget

this is the main file code :

   void main() {
    runApp(const MyApp());
  }

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

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Flutter Demo',
     theme: ThemeData(
       brightness: Brightness.light,
       primarySwatch: Colors.indigo,
     ),
     darkTheme: ThemeData(
       brightness: Brightness.dark,
       primarySwatch: Colors.indigo,
     ),
     themeMode: ThemeMode.light,
     home:  const HomePage(),
   );
 }
}

this is the homepage code:

   import 'package:flutter/material.dart';

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

     @override
     Widget build(BuildContext context) {
       return  DefaultTabController(
             length: 3,
             child: Scaffold(
                 appBar: AppBar(
                   title: const Text('App'),
                 ),
                 bottomNavigationBar:  Material(
                     color : Theme.of(context).primaryColor,
                   child: TabBar(
                     tabs: <Widget>[
                       Tab(
                         icon: Icon(Icons.calendar_today),
                         text: 'Planner',
                       ),
                       Tab(
                         icon: Icon(Icons.amp_stories),
                         text: 'Cards',
                       ),
                       Tab(
                         icon: Icon(Icons.auto_stories),
                         text: 'Notes',
                       ),
                     ],
                   ),
                 ),
                 body: const TabBarView(
                   children: <Widget>[CardsView(), NotesView(),PlannerView()],
                 )),
           );
     }
   }

.................

this is how it looks when you run the app:

and this is how it looks when you change the themeMode to: ThemeMode.dark


问:
reload an specific div without refresh whole page
I want to reload just an specific div. I searched and read some similar questions too. What I made is below. What is wrong with my code that does not refresh the div ?</p>
```<code><html>
    <body>
        <div id="reloadable">
            <?php include 'rand.php'; ?>
        </div>
        <button class="ref" onclick="refreshDiv();"> refresh </button>

        <script type="text/javacript">
            function refreshDiv()
            {
                $('#reloadable').load(location.href + ' #reloadable');
            }
        </script>
    </body>
</html>
</code>```
```<code><?php

$a= rand(0,10);
echo $a;

?>
</code>```

答:
The problem is that you're returning an entire HTML document when you use location.href as the URL. The documentation warns:

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , <title>, or  elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

Since you're returning the  element, this is being filtered out, so there's nothing to insert into #reloadable.

Instead, you could load directly from rand.php:

```<code>function refreshDiv()
{
    $('#reloadable').load('rand.php');
}
</code>```

Body:
I want to reload just an specific div. I searched and read some similar questions too. What I made is below. What is wrong with my code that does not refresh the div ?

            <?php include 'rand.php'; ?>

        <button class="ref" onclick="refreshDiv();"> refresh </button>

<?php

$a= rand(0,10);
echo $a;

?>

Body:
The problem is that you're returning an entire HTML document when you use location.href as the URL. The documentation warns:

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

Since you're returning the <html> element, this is being filtered out, so there's nothing to insert into #reloadable.

Instead, you could load directly from rand.php:

function refreshDiv()
{
    $('#reloadable').load('rand.php');
}


问:
How can I get all the related rows when using IN to filter?
This is what my query looks like:

```<code>select "spaces"."id" as "id",
  "spaces"."user_id" as "user_id",
  "spaces"."type" as "type",
  "spaces"."latitude" as "latitude",
  "spaces"."longitude" as "longitude",
  "categories"."category_id" as "categories:category_id"
  from "spaces"
  left join "spaces_categories" as "categories" on "categories"."space_id" = "spaces"."id"
  where "categories"."category_id" in ($)
  and ST_DWithin(spaces.geometry::geography, ST_SetSRID(ST_Point($,$), 4326)::geography, $)
</code>```

I am using pg 14.1

I am trying to find all spaces within a radius that meet the requested category Ids, along with all the categories for those spaces.

A space can have many category IDs, so if I search for category ids (1,2), and there happens to be 2 space results (and assume each space has 4 categories, 1,2,3,4), I would be expecting 8 rows.  However, my query only returns 4 rows, for categories 1,2.

How can I update my query so I can get all the categories, as long there is some overlap?

Is it due to my IN clause?

答:
And EXISTS subquery should do the trick:

SELECT s.id
     , s.user_id
     , s.type
     , s.latitude
     , s.longitude
     , c.category_id AS "categories:category_id"
FROM   spaces                 s
LEFT   JOIN spaces_categories c ON c.space_id = s.id
WHERE  st_dwithin(s.geometry::geography, st_setsrid(st_point($,$), 4326)::geography, $)
AND    EXISTS (
   SELECT FROM spaces_categories x
   WHERE  x.space_id = s.id
   AND    x.category_id IN ($)
   );
```

There are many other ways, but this should be fastest and clearest.

The cast from geometry to geography seems worrisome for performance, though. Do you have an expression index covering that?

Related:

How do I query all rows within a 5-mile radius of my coordinates?

How to find intersecting geographies between two tables recursively

Why is my spatial query slower in Postgres 13 than in Postgres 11?

ST_DWithin Calc Meters - transform or cast?

Body:
This is what my query looks like:

select "spaces"."id" as "id",
  "spaces"."user_id" as "user_id",
  "spaces"."type" as "type",
  "spaces"."latitude" as "latitude",
  "spaces"."longitude" as "longitude",
  "categories"."category_id" as "categories:category_id"
  from "spaces"
  left join "spaces_categories" as "categories" on "categories"."space_id" = "spaces"."id"
  where "categories"."category_id" in ($)
  and ST_DWithin(spaces.geometry::geography, ST_SetSRID(ST_Point($,$), 4326)::geography, $)

I am using pg 14.1

I am trying to find all spaces within a radius that meet the requested category Ids, along with all the categories for those spaces.

A space can have many category IDs, so if I search for category ids (1,2), and there happens to be 2 space results (and assume each space has 4 categories, 1,2,3,4), I would be expecting 8 rows.  However, my query only returns 4 rows, for categories 1,2.

How can I update my query so I can get all the categories, as long there is some overlap?

Is it due to my IN clause?

Body:
And EXISTS subquery should do the trick:

SELECT s.id
     , s.user_id
     , s.type
     , s.latitude
     , s.longitude
     , c.category_id AS "categories:category_id"
FROM   spaces                 s
LEFT   JOIN spaces_categories c ON c.space_id = s.id
WHERE  st_dwithin(s.geometry::geography, st_setsrid(st_point($,$), 4326)::geography, $)
AND    EXISTS (
   SELECT FROM spaces_categories x
   WHERE  x.space_id = s.id
   AND    x.category_id IN ($)
   );

There are many other ways, but this should be fastest and clearest.

The cast from geometry to geography seems worrisome for performance, though. Do you have an expression index covering that?

Related:

How do I query all rows within a 5-mile radius of my coordinates?

How to find intersecting geographies between two tables recursively

Why is my spatial query slower in Postgres 13 than in Postgres 11?

ST_DWithin Calc Meters - transform or cast?


问:
How to detect mobile (iOS and Android) using JSP/Java?
Just wondering if anyone has come across this?

Basically, Im looking to detect for iOS and Android using JSP and to be able to conditionally add CSS and JS files to the page.

Any ideas?

答:
A very simple solution would be:

```<code><%
  String userAgent = request.getHeader("user-agent");
  if (userAgent.matches(".*Android.*"))
  {
    out.print("You're an Android!");
  }
  else
  {
    out.print("You're something else..."); // iOS
  }
%>
</code>```

Because of the very short else-statement, this should be used only if you serve no more than iOS and Android.

Body:
A very simple solution would be:

<%
  String userAgent = request.getHeader("user-agent");
  if (userAgent.matches(".*Android.*"))
  {
    out.print("You're an Android!");
  }
  else
  {
    out.print("You're something else..."); // iOS
  }
%>

Because of the very short else-statement, this should be used only if you serve no more than iOS and Android.


问:
What exactly is "Viewport"?
I have troubles understanding what exactly "Viewport" is. The docs say it defines the "width" and the "height" in a "page". And what exactly was "page", again? I used to think of it as a browser tab, but this is also wrong, see below...

My tests fail because I seem to misunderstand "Viewport":

```<code>page.setViewport({ width: 640, height: 480 })
expect(window.innerWidth).toBe(640) // FAIL, it's 1366, Puppeteers default
</code>```

From googling around, I know that there are options to launch Puppeteer in another window size. But this is not what I'm looking for, out of two reasons:

it still doesn't explain what "Viewport" is

I can't "restart" Puppeteer in every single test (I'm testing responsive behavior)

https://puppeteer.github.io/puppeteer/docs/puppeteer.page.viewport

答:
You should expect the page.evaluate result of window.innerWidth.

Remember that the execution context inside of the page itself is different with puppeteer context.

```<code>import puppeteer, { Browser, BrowserContext, Page } from 'puppeteer'

const start = async () => {
    const browser: Browser = await puppeteer.launch({ headless: false })
    const page: Page = await browser.newPage()
    page.setViewport({ width: 640, height: 480 })
    await page.goto('http://www.samisite.com/test-csb2nf/id43.htm', { waitUntil: 'networkidle0' })
    expect(await page.evaluate(() => window.innerWidth)).toBe(640)
    console.log(await page.evaluate(() => window.innerWidth))
    await page.close()
    await browser.close()
}

;(async () => await start())()
</code>```

Title: What exactly is "Viewport"?

Body:
I have troubles understanding what exactly "Viewport" is. The docs say it defines the "width" and the "height" in a "page". And what exactly was "page", again? I used to think of it as a browser tab, but this is also wrong, see below...

My tests fail because I seem to misunderstand "Viewport":

page.setViewport({ width: 640, height: 480 })
expect(window.innerWidth).toBe(640) // FAIL, it's 1366, Puppeteers default

From googling around, I know that there are options to launch Puppeteer in another window size. But this is not what I'm looking for, out of two reasons:

it still doesn't explain what "Viewport" is

I can't "restart" Puppeteer in every single test (I'm testing responsive behavior)

https://puppeteer.github.io/puppeteer/docs/puppeteer.page.viewport

Body:
You should expect the page.evaluate result of window.innerWidth.

Remember that the execution context inside of the page itself is different with puppeteer context.

import puppeteer, { Browser, BrowserContext, Page } from 'puppeteer'

const start = async () => {
    const browser: Browser = await puppeteer.launch({ headless: false })
    const page: Page = await browser.newPage()
    page.setViewport({ width: 640, height: 480 })
    await page.goto('http://www.samisite.com/test-csb2nf/id43.htm', { waitUntil: 'networkidle0' })
    expect(await page.evaluate(() => window.innerWidth)).toBe(640)
    console.log(await page.evaluate(() => window.innerWidth))
    await page.close()
    await browser.close()
}

;(async () => await start())()


问:
How to use ConfigMap configuration with Helm NginX Ingress controller - Kubernetes
I've found a documentation about how to configure your NginX ingress controller using ConfigMap: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/

Unfortunately I've no idea and couldn't find it anywhere how to load that ConfigMap from my Ingress controller.

My ingress controller:

```<code>helm install --name ingress --namespace ingress-nginx --set rbac.create=true,controller.kind=DaemonSet,controller.service.type=ClusterIP,controller.hostNetwork=true stable/nginx-ingress
</code>```

My config map:

```<code>kind: ConfigMap
apiVersion: v1
metadata:
  name: ingress-configmap
data:
  proxy-read-timeout: "86400s"
  client-max-body-size: "2g"
  use-http2: "false"
</code>```

My ingress:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress
  annotations:
    nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
spec:
  tls:
    - hosts:
        - my.endpoint.net
      secretName: ingress-tls
  rules:
    - host: my.endpoint.net
      http:
        paths:
          - path: /
            backend:
              serviceName: web
              servicePort: 443
          - path: /api
            backend:
              serviceName: api
              servicePort: 443
</code>```

How do I make my Ingress to load the configuration from the ConfigMap?

答:
Based on the NeverEndingQueue's answer I want to provide an update for Kubernetes v1.23 / Helm 3

This is my installation command + --dry-run --debug part:
helm upgrade --install ingress-nginx ingress-nginx/ingress-nginx --namespace ingress-nginx --create-namespace --dry-run --debug

This is the part we need from the generated output of the command above:

```<code>apiVersion: apps/v1
kind: DaemonSet
metadata:
  ...
spec:
  ...
  template:
    ...
    spec:
      dnsPolicy: ClusterFirst
      containers:
        - name: controller
          ...
          args:
            - /nginx-ingress-controller
            - --publish-service=$(POD_NAMESPACE)/ingress-nginx-controller
            - --...
            - --configmap=${POD_NAMESPACE}/ingress-nginx-controller
            - --...
            ....
</code>```

We need this part: --configmap=${POD_NAMESPACE}/ingress-nginx-controller.

As you can see, name of ConfigMap must be ingress-nginx-controller and namespace must be the one you use during chart installation (ie {POD_NAMESPACE}, in my example about this is --namespace ingress-nginx).

```<code># nginx-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: ingress-nginx-controller
  namespace: ingress-nginx
data:
  map-hash-bucket-size: "128"
</code>```

Then run kubectl apply -f nginx-config.yaml to apply ConfigMap and nginx's pod(s) will be auto-reloaded with updated config.

To check, that nginx config has been updated, find name of nginx's pod (you can use any one, if you have few nodes): kubectl get pods -n ingress-nginx (or kubectl get pods -A)

and then check config: kubectl exec -it ingress-nginx-controller-{generatedByKubernetesId} -n ingress-nginx cat /etc/nginx/nginx.conf

UPDATE:

The correct name (ie name: ingress-nginx-controller) is shown in the official docs. Conclusion: no need to reinvent the wheel.

Body:
I've found a documentation about how to configure your NginX ingress controller using ConfigMap: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/

Unfortunately I've no idea and couldn't find it anywhere how to load that ConfigMap from my Ingress controller.

My ingress controller:

helm install --name ingress --namespace ingress-nginx --set rbac.create=true,controller.kind=DaemonSet,controller.service.type=ClusterIP,controller.hostNetwork=true stable/nginx-ingress

My config map:

kind: ConfigMap
apiVersion: v1
metadata:
  name: ingress-configmap
data:
  proxy-read-timeout: "86400s"
  client-max-body-size: "2g"
  use-http2: "false"

My ingress:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress
  annotations:
    nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
spec:
  tls:
    - hosts:
        - my.endpoint.net
      secretName: ingress-tls
  rules:
    - host: my.endpoint.net
      http:
        paths:
          - path: /
            backend:
              serviceName: web
              servicePort: 443
          - path: /api
            backend:
              serviceName: api
              servicePort: 443

How do I make my Ingress to load the configuration from the ConfigMap?

Body:
Based on the NeverEndingQueue's answer I want to provide an update for Kubernetes v1.23 / Helm 3

This is my installation command + --dry-run --debug part:
helm upgrade --install ingress-nginx ingress-nginx/ingress-nginx --namespace ingress-nginx --create-namespace --dry-run --debug

This is the part we need from the generated output of the command above:

apiVersion: apps/v1
kind: DaemonSet
metadata:
  ...
spec:
  ...
  template:
    ...
    spec:
      dnsPolicy: ClusterFirst
      containers:
        - name: controller
          ...
          args:
            - /nginx-ingress-controller
            - --publish-service=$(POD_NAMESPACE)/ingress-nginx-controller
            - --...
            - --configmap=${POD_NAMESPACE}/ingress-nginx-controller
            - --...
            ....

We need this part: --configmap=${POD_NAMESPACE}/ingress-nginx-controller.

As you can see, name of ConfigMap must be ingress-nginx-controller and namespace must be the one you use during chart installation (ie {POD_NAMESPACE}, in my example about this is --namespace ingress-nginx).

# nginx-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: ingress-nginx-controller
  namespace: ingress-nginx
data:
  map-hash-bucket-size: "128"

Then run kubectl apply -f nginx-config.yaml to apply ConfigMap and nginx's pod(s) will be auto-reloaded with updated config.

To check, that nginx config has been updated, find name of nginx's pod (you can use any one, if you have few nodes): kubectl get pods -n ingress-nginx (or kubectl get pods -A)

and then check config: kubectl exec -it ingress-nginx-controller-{generatedByKubernetesId} -n ingress-nginx cat /etc/nginx/nginx.conf

UPDATE:

The correct name (ie name: ingress-nginx-controller) is shown in the official docs. Conclusion: no need to reinvent the wheel.


问:
Quartz X11 under Yosemite does not respect Alt key
I don't use it often, but now (after Yosemite came) I opened the XQuartz terminal and tried to enter ssh -X user@machine. But it did no longer accept the alt-key being pressed. None of the alt-chars shows up. It's always the original letter appearing. For the time being I ended up using a shell command with the at-sign inside and calling that, but that can't be the final solution. Note: I have already checked all combinations of the Input settings in the preferences for the keyboard. I also rebooted (feel like a Windoze user meanwhile).

答: I had the same problem, at the end I updated XQuartz, but maybe only with checking the option that says "Option keys send Alt_L and Alt_R" and restarting should work</p>


问:
How to set the bottom margin of a modal
I'm having a problem opening the modal. What I notice is that there is no lower margin of the modal, as you can see from the figure.

I have added JavaScript in case anyone cares.

So you can see where the modal starts from but not where it ends. How can I solve this problem?
Can you kindly help me?

var modal = document.getElementById("myModal");

var btn = document.getElementById("myBtn");

var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
            display: none;
            position: fixed;
            z-index: 1;
            padding-top: 100px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgb(0, 0, 0);
            background-color: rgba(0, 0, 0, 0.4);
            }

        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            z-index: 999;
        }</code>```

                        ×

```

答:
It seems you are adding the margin to the wrong element. Just change

```<code>.mycontent{
    margin-bottom: 10%;
}
</code>```

To this instead

```<code>.modal-content{
    margin-bottom: 10%;
}
</code>```

Title: How to set the bottom margin of a modal

Body:
I'm having a problem opening the modal. What I notice is that there is no lower margin of the modal, as you can see from the figure.

I have added JavaScript in case anyone cares.

So you can see where the modal starts from but not where it ends. How can I solve this problem?
Can you kindly help me?

var modal = document.getElementById("myModal");

var btn = document.getElementById("myBtn");

var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

.modal {
            display: none;
            position: fixed;
            z-index: 1;
            padding-top: 100px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgb(0, 0, 0);
            background-color: rgba(0, 0, 0, 0.4);
            }

        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            z-index: 999;
        }

                        ×

Body:
It seems you are adding the margin to the wrong element. Just change

.mycontent{
    margin-bottom: 10%;
}

To this instead

.modal-content{
    margin-bottom: 10%;
}


问:
How do I return an array of object references with a specific length?
I have an array of object references with a size of 100. The array is filled with 4 object references while the rest of it is empty. What I want to do is return the array with only those 4 references. I tried creating a new array and copying the references into it, but then I always get an error saying the array is null when I try to invoke the method. Here's the code:</p>
```<code>public Robots[] getRobots() {
        for(int i = 0; i < robots.length; i++) {
            if(robots[i] != null)
                count++;
        }
        Robots[] newRobots = new Robots[count];
        newRobots = Arrays.copyOfRange(robots, 0, count);
        return newRobots;
    }
</code>```

答:
I suppose you need to fix 2 errors:

clear the count variable

don't assume that all not null objects are at the beginning

here is the fixed code:

```<code>public Robots[] getRobots() {
    int count = 0;
    for(int i = 0; i < robots.length; i++) {
        if(robots[i] != null)
            count++;
    }
    Robots[] newRobots = new Robots[count];

    count = 0;
    for(int i = 0; i < robots.length; i++) {
        if(robots[i] != null)
            newRobots[count++] = robots[i];
    }
    return newRobots;
}
</code>```

Body:
I have an array of object references with a size of 100. The array is filled with 4 object references while the rest of it is empty. What I want to do is return the array with only those 4 references. I tried creating a new array and copying the references into it, but then I always get an error saying the array is null when I try to invoke the method. Here's the code:

public Robots[] getRobots() {
        for(int i = 0; i < robots.length; i++) {
            if(robots[i] != null)
                count++;
        }
        Robots[] newRobots = new Robots[count];
        newRobots = Arrays.copyOfRange(robots, 0, count);
        return newRobots;
    }

Body:
I suppose you need to fix 2 errors:

clear the count variable

don't assume that all not null objects are at the beginning

here is the fixed code:

public Robots[] getRobots() {
    int count = 0;
    for(int i = 0; i < robots.length; i++) {
        if(robots[i] != null)
            count++;
    }
    Robots[] newRobots = new Robots[count];

    count = 0;
    for(int i = 0; i < robots.length; i++) {
        if(robots[i] != null)
            newRobots[count++] = robots[i];
    }
    return newRobots;
}


问:
Splitting Contents of a File
So I have a file with a list of users in the format like this:

michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash
abigail:&i4KZ5wmac566:501:501:Abigail Smith:/home/abigail:/bin/tcsh

What I need to do is just extract the passwords from the file which in this case are:
"atbWfKL4etk4U" and "&i4KZ5wmac566" and to store them into an array.

This is what I have so far:

```<code>public static void main(String[] args) throws IOException{

    // Create a scanner for keyboard input
    Scanner scan = new Scanner(System.in);

    // Prompt user to select a file to open
    System.out.print("Enter the path of the file: ");
    String filename = scan.nextLine();

    // Open the file
    File file = new File(filename);
    Scanner inputFile = new Scanner(file);

    // Create Array to store each user password in
    String[] passwords = {};

    // Close the file
    scan.close();
    inputFile.close();

}
</code>```

答:
This looks like a typical CSV type file format and because there is an unknown number of Users in the file and the fact that arrays can not dynamically grow it's a good idea to utilize an ArrayList which can grow dynamically and then convert that list to a String array, for example:

The following method assumes there is No Header Line within the data file:

```<code>public static String[] getPasswordsFromFile(String filePath) {
    List<String> passwordsList = new ArrayList<>();
    File file = new File(filePath);
    try (Scanner reader = new Scanner(file)) {
        String line = "";
        while (reader.hasNextLine()) {
            line = reader.nextLine().trim();
            // Skip blank lines (if any).
            if (line.isEmpty()) {
                continue;
            }
            /* Split out the password from the file data line:
               The Regular Expression (RegEx) below splits each
               encountered file line based on the Colon(:) delimiter
               but also handles any possible whitespaces before
               or after that delimiter:                 */
            String linePassword = line.split("\\s*\\:\\s*")[1];

            // If there is no password there then apply "N/A":
            if (linePassword.isEmpty()) {
                linePassword = "N/A";
            }
            // Add the password to the List
            passwordsList.add(linePassword);
        }
    }
    catch (FileNotFoundException ex) {
        // Handle the exception (if any) the way you like...
        System.err.println(ex.getMessage());
    }

    // Convert the List<String> to String[] Array and return:
    return passwordsList.toArray(new String[passwordsList.size()]);
}
</code>```

How you might use a method like this:

```<code>// Create a scanner object for keyboard input
Scanner userInput = new Scanner(System.in);

// Prompt user to select a file to open with validation:
String fileName = "";
// -----------------------------------
while (fileName.isEmpty()) {
    System.out.print("Enter the path of the file (c to cancel): --> ");
    fileName = userInput.nextLine();
    if (fileName.equalsIgnoreCase("c")) {
        System.out.println("Process Canceled! Quiting.");
        System.exit(0);
    }
    if (!new File(fileName).exists()) {
        System.out.println("Invalid Entry! Try again...\n");
        fileName = "";
    }
}
// -----------------------------------

/* OR - you could have........
// -----------------------------------
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new File("").getAbsolutePath());
fc.showDialog(new JDialog(), "get Passwords");
if (fc.getSelectedFile() != null) {
    fileName = fc.getSelectedFile().getAbsolutePath();
}
else {
    System.out.println("Process Canceled! Quiting.");
    System.exit(0);
}
// -----------------------------------
*/

// Get the Passwords from file:
String[] passwords = getPasswordsFromFile("UserData.txt");
// Display the Passwords retrieved:
System.out.println();
System.out.println("Passwords from file:");
System.out.println("====================");

for (String str : passwords) {
    System.out.println(str);
}
</code>```

If you were to run this code against a file which contains the data you provided within your post,your console window will diplay:

```<code>Enter the path of the file (c to cancel): --> userData.txt

Passwords from file:
====================
atbWfKL4etk4U
&i4KZ5wmac566
</code>```

Title: Splitting Contents of a File

Body:
So I have a file with a list of users in the format like this:

michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash
abigail:&i4KZ5wmac566:501:501:Abigail Smith:/home/abigail:/bin/tcsh

What I need to do is just extract the passwords from the file which in this case are:
"atbWfKL4etk4U" and "&i4KZ5wmac566" and to store them into an array.

This is what I have so far:

public static void main(String[] args) throws IOException{

    // Create a scanner for keyboard input
    Scanner scan = new Scanner(System.in);

    // Prompt user to select a file to open
    System.out.print("Enter the path of the file: ");
    String filename = scan.nextLine();

    // Open the file
    File file = new File(filename);
    Scanner inputFile = new Scanner(file);

    // Create Array to store each user password in
    String[] passwords = {};

    // Close the file
    scan.close();
    inputFile.close();

}

Body:
This looks like a typical CSV type file format and because there is an unknown number of Users in the file and the fact that arrays can not dynamically grow it's a good idea to utilize an ArrayList which can grow dynamically and then convert that list to a String array, for example:

The following method assumes there is No Header Line within the data file:

public static String[] getPasswordsFromFile(String filePath) {
    List<String> passwordsList = new ArrayList<>();
    File file = new File(filePath);
    try (Scanner reader = new Scanner(file)) {
        String line = "";
        while (reader.hasNextLine()) {
            line = reader.nextLine().trim();
            // Skip blank lines (if any).
            if (line.isEmpty()) {
                continue;
            }
            /* Split out the password from the file data line:
               The Regular Expression (RegEx) below splits each
               encountered file line based on the Colon(:) delimiter
               but also handles any possible whitespaces before
               or after that delimiter:                 */
            String linePassword = line.split("\\s*\\:\\s*")[1];

            // If there is no password there then apply "N/A":
            if (linePassword.isEmpty()) {
                linePassword = "N/A";
            }
            // Add the password to the List
            passwordsList.add(linePassword);
        }
    }
    catch (FileNotFoundException ex) {
        // Handle the exception (if any) the way you like...
        System.err.println(ex.getMessage());
    }

    // Convert the List<String> to String[] Array and return:
    return passwordsList.toArray(new String[passwordsList.size()]);
}

How you might use a method like this:

// Create a scanner object for keyboard input
Scanner userInput = new Scanner(System.in);

// Prompt user to select a file to open with validation:
String fileName = "";
// -----------------------------------
while (fileName.isEmpty()) {
    System.out.print("Enter the path of the file (c to cancel): --> ");
    fileName = userInput.nextLine();
    if (fileName.equalsIgnoreCase("c")) {
        System.out.println("Process Canceled! Quiting.");
        System.exit(0);
    }
    if (!new File(fileName).exists()) {
        System.out.println("Invalid Entry! Try again...\n");
        fileName = "";
    }
}
// -----------------------------------

/* OR - you could have........
// -----------------------------------
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new File("").getAbsolutePath());
fc.showDialog(new JDialog(), "get Passwords");
if (fc.getSelectedFile() != null) {
    fileName = fc.getSelectedFile().getAbsolutePath();
}
else {
    System.out.println("Process Canceled! Quiting.");
    System.exit(0);
}
// -----------------------------------
*/

// Get the Passwords from file:
String[] passwords = getPasswordsFromFile("UserData.txt");
// Display the Passwords retrieved:
System.out.println();
System.out.println("Passwords from file:");
System.out.println("====================");

for (String str : passwords) {
    System.out.println(str);
}

If you were to run this code against a file which contains the data you provided within your post,your console window will diplay:

Enter the path of the file (c to cancel): --> userData.txt

Passwords from file:
====================
atbWfKL4etk4U
&i4KZ5wmac566


问:
How to find updated S3 bucket size via console?
The Storage Metrics for Amazon S3 Bucket is updated once in a day.

I observed that via CLI, I get the updated size of bucket as required, but via console it is only once per day.

How can I customize the metric via console where I can get the updated bucket Storage size once in every 30 minutes?

答:
You cannot change the update frequency of the size shown in the S3 management console.

However, you could use the AWS Command-Line Interface (CLI) to make API calls to S3 to calculate the size.

From AWS S3: how do I see how much disk space is using:

```<code>aws s3 ls s3://mybucket --recursive --human-readable --summarize
</code>```

However, if the bucket has many objects (eg 100,000+), this can take considerable time to calculate.

Body:
You cannot change the update frequency of the size shown in the S3 management console.

However, you could use the AWS Command-Line Interface (CLI) to make API calls to S3 to calculate the size.

From AWS S3: how do I see how much disk space is using:

aws s3 ls s3://mybucket --recursive --human-readable --summarize

However, if the bucket has many objects (eg 100,000+), this can take considerable time to calculate.


问:
How do I plot two regression lines on the same plot with different x and y?
I am required to fit two simple linear regression lines, one with "y = father" and "x = son", the other with "y = son" and "x = father". I was able to do this with no issues and have gathered the correct equations. However, I am also required to plot them on the same scatterplot which is where I am running into some trouble. I am curious if there is a way I can plot the "y = father" and "x = son" regression line onto the scatterplot where y = son and x = father. Or is there a way I can combine the following two plots?

```<code>ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(slope = 0.46139, intercept = 37.28761, col = "blue") +
   theme_bw()
</code>```
```<code>ggplot(galton_heights, aes(x = son, y = father)) +
   geom_point() +
   geom_abline(slope = 0.40713, intercept = 40.93831, col = "red") +
   coord_flip() +
   theme_bw()
</code>```

I was told my plot should look similar to this which is the two separate graphs I have above combined together.

答:
for the first part, you can simply use the geom_smooth to draw a linear regression line:

```<code>ggplot(galton_heights, aes(x = father, y = son)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  theme_bw
</code>```

For the second part of the question, it doesn't really make sense to do it, as you should change the axis. You can do that:

```<code>ggplot(galton_heights, aes(x = father, y = son)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, col = "blue") +
  geom_smooth(aes(y = father, x = son), method = "lm", se = FALSE, col = "red") +
 theme_bw()
</code>```

But it is theoretically wrong.

Body:
I am required to fit two simple linear regression lines, one with "y = father" and "x = son", the other with "y = son" and "x = father". I was able to do this with no issues and have gathered the correct equations. However, I am also required to plot them on the same scatterplot which is where I am running into some trouble. I am curious if there is a way I can plot the "y = father" and "x = son" regression line onto the scatterplot where y = son and x = father. Or is there a way I can combine the following two plots?

ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(slope = 0.46139, intercept = 37.28761, col = "blue") +
   theme_bw()

ggplot(galton_heights, aes(x = son, y = father)) +
   geom_point() +
   geom_abline(slope = 0.40713, intercept = 40.93831, col = "red") +
   coord_flip() +
   theme_bw()

I was told my plot should look similar to this which is the two separate graphs I have above combined together.

Body:
for the first part, you can simply use the geom_smooth to draw a linear regression line:

ggplot(galton_heights, aes(x = father, y = son)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  theme_bw

For the second part of the question, it doesn't really make sense to do it, as you should change the axis. You can do that:

ggplot(galton_heights, aes(x = father, y = son)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, col = "blue") +
  geom_smooth(aes(y = father, x = son), method = "lm", se = FALSE, col = "red") +
 theme_bw()

But it is theoretically wrong.