问:
cx_Oracle version check
I'm using PyCharm 2019.1 Professional and am able to connect to an Oracle JDBC database using a thin driver (jdbc:oracle:thin:@host:PORT:SID). I'm trying to use the cx_Oracle library (version 1.1.9) and Anaconda 3.6, but do not seem to have the functions .connect or .makedsn with the library. I find this unusual, and at a loss.

Do I just have the wrong cx_Oracle version even though I installed using pip?

Is the 1.1.9 version that works with Anaconda 3.6 just not have these functions?

Or is there a different/easier library I can use to connect with jdbc:oracle:thin:@host:PORT:SID?

dir(cx_Oracle)
```

Outputs:

['ARRAY',  'BIGINT',  'BINARY',  'BLANK_SCHEMA',  'BLOB',  'BOOLEAN',
'BigInteger',  'Binary',  'Boolean',  'CHAR',  'CLOB',
'CheckConstraint',  'Column',  'ColumnDefault',  'Constraint',
'DATE',  'DATETIME',  'DDL',  'DECIMAL',  'Date',  'DateTime',
'DefaultClause',  'Enum',  'FLOAT',  'FetchedValue',  'Float',
'ForeignKey',  'ForeignKeyConstraint',  'INT',  'INTEGER',  'Index',
'Integer',  'Interval',  'JSON',  'LargeBinary',  'MetaData',
'NCHAR',  'NUMERIC',  'NVARCHAR',  'Numeric',  'PassiveDefault',
'PickleType',  'PrimaryKeyConstraint',  'REAL',  'SMALLINT',
'Sequence',  'SmallInteger',  'String',  'TEXT',  'TIME',
'TIMESTAMP',  'Table',  'Text',  'ThreadLocalMetaData',  'Time',
'TypeDecorator',  'Unicode',  'UnicodeText',  'UniqueConstraint',
'VARBINARY',  'VARCHAR',  'all',  'builtins',  'cached',
'doc',  'file',  'go',  'loader',  'name',
'package',  'path',  'spec',  'version',  'alias',
'all',  'and',  'any_',  'asc',  'between',  'bindparam',  'case',
'cast',  'collate',  'column',  'create_engine',  'delete',  'desc',
'distinct',  'engine',  'engine_from_config',  'event',  'events',
'exc',  'except_',  'except_all',  'exists',  'extract',  'false',
'func',  'funcfilter',  'insert',  'inspect',  'inspection',
'interfaces',  'intersect',  'intersect_all',  'join',  'lateral',
'literal',  'literal_column',  'log',  'modifier',  'not_',  'null',
'or_',  'outerjoin',  'outparam',  'over',  'pool',  'processors',
'schema',  'select',  'sql',  'subquery',  'table',  'tablesample',
'text',  'true',  'tuple_',  'type_coerce',  'types',  'union',
'union_all',  'update',  'util',  'within_group']

答:
To check the version of cx_Oracle

You must have python

Use your python shell, command prompt, or your code/text editor

Print out the following code

```<code>C:\Users>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec  6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle
>>> print(cx_Oracle.version)
8.3.0
>>> exit()
</code>```

Title: cx_Oracle version check

Body:
I'm using PyCharm 2019.1 Professional and am able to connect to an Oracle JDBC database using a thin driver (jdbc:oracle:thin:@host:PORT:SID). I'm trying to use the cx_Oracle library (version 1.1.9) and Anaconda 3.6, but do not seem to have the functions .connect or .makedsn with the library. I find this unusual, and at a loss.

Do I just have the wrong cx_Oracle version even though I installed using pip?

Is the 1.1.9 version that works with Anaconda 3.6 just not have these functions?

Or is there a different/easier library I can use to connect with jdbc:oracle:thin:@host:PORT:SID?

dir(cx_Oracle)

Outputs:

['ARRAY',  'BIGINT',  'BINARY',  'BLANK_SCHEMA',  'BLOB',  'BOOLEAN',
'BigInteger',  'Binary',  'Boolean',  'CHAR',  'CLOB',
'CheckConstraint',  'Column',  'ColumnDefault',  'Constraint',
'DATE',  'DATETIME',  'DDL',  'DECIMAL',  'Date',  'DateTime',
'DefaultClause',  'Enum',  'FLOAT',  'FetchedValue',  'Float',
'ForeignKey',  'ForeignKeyConstraint',  'INT',  'INTEGER',  'Index',
'Integer',  'Interval',  'JSON',  'LargeBinary',  'MetaData',
'NCHAR',  'NUMERIC',  'NVARCHAR',  'Numeric',  'PassiveDefault',
'PickleType',  'PrimaryKeyConstraint',  'REAL',  'SMALLINT',
'Sequence',  'SmallInteger',  'String',  'TEXT',  'TIME',
'TIMESTAMP',  'Table',  'Text',  'ThreadLocalMetaData',  'Time',
'TypeDecorator',  'Unicode',  'UnicodeText',  'UniqueConstraint',
'VARBINARY',  'VARCHAR',  'all',  'builtins',  'cached',
'doc',  'file',  'go',  'loader',  'name',
'package',  'path',  'spec',  'version',  'alias',
'all',  'and',  'any_',  'asc',  'between',  'bindparam',  'case',
'cast',  'collate',  'column',  'create_engine',  'delete',  'desc',
'distinct',  'engine',  'engine_from_config',  'event',  'events',
'exc',  'except_',  'except_all',  'exists',  'extract',  'false',
'func',  'funcfilter',  'insert',  'inspect',  'inspection',
'interfaces',  'intersect',  'intersect_all',  'join',  'lateral',
'literal',  'literal_column',  'log',  'modifier',  'not_',  'null',
'or_',  'outerjoin',  'outparam',  'over',  'pool',  'processors',
'schema',  'select',  'sql',  'subquery',  'table',  'tablesample',
'text',  'true',  'tuple_',  'type_coerce',  'types',  'union',
'union_all',  'update',  'util',  'within_group']

Body:
To check the version of cx_Oracle

You must have python

Use your python shell, command prompt, or your code/text editor

Print out the following code

C:\Users>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec  6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle
>>> print(cx_Oracle.version)
8.3.0
>>> exit()


来源: stackexchange

问:
Embed a map with satellite terrain active (iframe)
I have this iframe, generated in Google Maps.

```<code><iframe src="https://www.google.com/maps/d/u/0/embed?mid=1ssxg5qgL8pDlVKV4Jcc4axK_O9s2DYm2&ehbc=2E312F" width="100%" height="480"></iframe>
</code>```

I would like to know if it is possible force the map to be displayed with the satellite image activated. Thanks.

答:
Yes, it is possible, but you need to change it in MyMaps before you create the embedded <frame>.  See: http://www.geocodezip.com/SO_20220206_embeddedSat.html

The top map is your original, the bottom map is a copy with the base map changed "satellite".

To change the base map, click on "Base Map" in the left hand menu:

Then choose the image of the satellite tiles:

Then share and capture the new embedded  with a potentially new URL (might actually be the same).

ContentLicense: CC BY-SA 4.0

Body:
I have this iframe, generated in Google Maps.

I would like to know if it is possible force the map to be displayed with the satellite image activated. Thanks.

Body:
Yes, it is possible, but you need to change it in MyMaps before you create the embedded <frame>.  See: http://www.geocodezip.com/SO_20220206_embeddedSat.html

The top map is your original, the bottom map is a copy with the base map changed "satellite".

To change the base map, click on "Base Map" in the left hand menu:

Then choose the image of the satellite tiles:

Then share and capture the new embedded <iframe> with a potentially new URL (might actually be the same).


问:
Updating Java PriorityQueue when its elements change priority
I'm trying to use a PriorityQueue to order objects using a Comparator.

This can be achieved easily, but the objects class variables (with which the comparator calculates priority) may change after the initial insertion. Most people have suggested the simple solution of removing the object, updating the values and reinserting it again, as this is when the priority queue's comparator is put into action.

Is there a better way other than just creating a wrapper class around the PriorityQueue to do this?

答:
Is there a better way other than just creating a wrapper class around the PriorityQueue to do this?

It depends on the definition of "better" and the implementation of the wrapper.

If the implementation of the wrapper is to re-insert the value using the PriorityQueue's .remove(...) and .add(...) methods,
it's important to point out that .remove(...) runs in O(n) time.
Depending on the heap implementation,
updating the priority of a value can be done in O(log n) or even O(1) time,
therefore this wrapper suggestion may fall short of common expectations.

If you want to minimize your effort to implement,
as well as the risk of bugs of any custom solution,
then a wrapper that performs re-insert looks easy and safe.

If you want the implementation to be faster than O(n),
then you have some options:

Implement a heap yourself. The wikipedia entry describes multiple variants with their properties. This approach is likely to get your the best performance, at the same time the more code you write yourself, the greater the risk of bugs.

Implement a different kind of wrapper: handlee updating the priority by marking the entry as removed, and add a new entry with the revised priority.
This is relatively easy to do (less code), see below, though it has its own caveats.

I came across the second idea in Python's documentation,
and applied it to implement a reusable data structure in Java (see caveats at the bottom):

```<code>public class UpdatableHeap<T> {

  private final PriorityQueue<Node<T>> pq = new PriorityQueue<>(Comparator.comparingInt(node -> node.priority));
  private final Map<T, Node<T>> entries = new HashMap<>();

  public void addOrUpdate(T value, int priority) {
    if (entries.containsKey(value)) {
      entries.remove(value).removed = true;
    }

    Node<T> node = new Node<>(value, priority);
    entries.put(value, node);
    pq.add(node);
  }

  public T pop() {
    while (!pq.isEmpty()) {
      Node<T> node = pq.poll();
      if (!node.removed) {
        entries.remove(node.value);
        return node.value;
      }
    }

    throw new IllegalStateException("pop from empty heap");
  }

  public boolean isEmpty() {
    return entries.isEmpty();
  }

  private static class Node<T> {
    private final T value;
    private final int priority;
    private boolean removed = false;

    private Node(T value, int priority) {
      this.value = value;
      this.priority = priority;
    }
  }
}
</code>```

Note some caveats:

Entries marked removed stay in memory until they are popped

This can be unacceptable in use cases with very frequent updates

The internal Node wrapped around the actual values is an extra memory overhead (constant per entry). There is also an internal Map, mapping all the values currently in the priority queue to their Node wrapper.

Since the values are used in a map, users must be aware of the usual cautions when using a map, and make sure to have appropriate equals and hashCode implementations.

ContentLicense: CC BY-SA 3.0

Body:
Is there a better way other than just creating a wrapper class around the PriorityQueue to do this?

It depends on the definition of "better" and the implementation of the wrapper.

If the implementation of the wrapper is to re-insert the value using the PriorityQueue's .remove(...) and .add(...) methods,
it's important to point out that .remove(...) runs in O(n) time.
Depending on the heap implementation,
updating the priority of a value can be done in O(log n) or even O(1) time,
therefore this wrapper suggestion may fall short of common expectations.

If you want to minimize your effort to implement,
as well as the risk of bugs of any custom solution,
then a wrapper that performs re-insert looks easy and safe.

If you want the implementation to be faster than O(n),
then you have some options:

Implement a heap yourself. The wikipedia entry describes multiple variants with their properties. This approach is likely to get your the best performance, at the same time the more code you write yourself, the greater the risk of bugs.

Implement a different kind of wrapper: handlee updating the priority by marking the entry as removed, and add a new entry with the revised priority.
This is relatively easy to do (less code), see below, though it has its own caveats.

I came across the second idea in Python's documentation,
and applied it to implement a reusable data structure in Java (see caveats at the bottom):

public class UpdatableHeap<T> {

  private final PriorityQueue<Node<T>> pq = new PriorityQueue<>(Comparator.comparingInt(node -> node.priority));
  private final Map<T, Node<T>> entries = new HashMap<>();

  public void addOrUpdate(T value, int priority) {
    if (entries.containsKey(value)) {
      entries.remove(value).removed = true;
    }

    Node<T> node = new Node<>(value, priority);
    entries.put(value, node);
    pq.add(node);
  }

  public T pop() {
    while (!pq.isEmpty()) {
      Node<T> node = pq.poll();
      if (!node.removed) {
        entries.remove(node.value);
        return node.value;
      }
    }

    throw new IllegalStateException("pop from empty heap");
  }

  public boolean isEmpty() {
    return entries.isEmpty();
  }

  private static class Node<T> {
    private final T value;
    private final int priority;
    private boolean removed = false;

    private Node(T value, int priority) {
      this.value = value;
      this.priority = priority;
    }
  }
}

Note some caveats:

Entries marked removed stay in memory until they are popped

This can be unacceptable in use cases with very frequent updates

The internal Node wrapped around the actual values is an extra memory overhead (constant per entry). There is also an internal Map, mapping all the values currently in the priority queue to their Node wrapper.

Since the values are used in a map, users must be aware of the usual cautions when using a map, and make sure to have appropriate equals and hashCode implementations.


问:
Stop a function returning an array of objects from firestore from running continuously running SwiftUI
The function is returning the arrays from a snapshot and using them as the output of the function. I am calling the function is a separate view which maps out the arrays. However, the function does not stop running after I open that view.

```<code>    func fetchReplies(post: Post) -> [Post] {
        let query = COLLECTION_POSTS.document(post.id).collection("post-replies")
            .order(by: "timestamp", descending: true)

        query.getDocuments { snapshot, _ in

            guard let documents = snapshot?.documents else { return }
            self.post = documents.map({ Post(dictionary: $0.data()) })
        }
        print(DateInterval())
        return self.post
    }
</code>```

I am calling the function in the view like this.

```<code>ScrollView() {
                LazyVStack {
                    ForEach(repliesViewModel.fetchReplies(post: self.post)) { post in
                        PostCell(post: post)
                            .padding(.horizontal)
                            .padding(.top, 10)
                    }
                }
            }
</code>```

The replies are populating the view but its calling the function repeatedly even after leaving view. I have the Date object there so that I can see it firing.

答:
There is a lot wrong with your code.

Your fetchReplies() function calls the async getDocuments(completion:) function. getDocuments(completion:) won't finish until after your fetchReplies() has returned, so you can't have fetchReplies() return a result. You need to make fetchReplies() take a completion handler. Something like this:

```<code>func fetchReplies(post: Post, completion: (Post) -> Void){
    let query = COLLECTION_POSTS.document(post.id).collection("post-replies")
        .order(by: "timestamp", descending: true)

    query.getDocuments { snapshot, _ in

        guard let documents = snapshot?.documents else { return }
        completion(documents.map({ Post(dictionary: $0.data()) })
        )
    }
    print(DateInterval())
}
</code>```

You call fetchReplies() in a ForEach, which must return a View synchronously. You can't do that. For one thing, it will call fetchReplies repeatedly. For another, fetchReplies() is (or should be) an async function, so it can't return it's results synchronously like it needs to in order to create a View.

I guess you will need to build your Views empty, and then install your data into them once fetchReplies() function's completion handler fires. (I'm not very experienced with SwiftUI.)

Body:
The function is returning the arrays from a snapshot and using them as the output of the function. I am calling the function is a separate view which maps out the arrays. However, the function does not stop running after I open that view.

    func fetchReplies(post: Post) -> [Post] {
        let query = COLLECTION_POSTS.document(post.id).collection("post-replies")
            .order(by: "timestamp", descending: true)

        query.getDocuments { snapshot, _ in

            guard let documents = snapshot?.documents else { return }
            self.post = documents.map({ Post(dictionary: $0.data()) })
        }
        print(DateInterval())
        return self.post
    }

I am calling the function in the view like this.

ScrollView() {
                LazyVStack {
                    ForEach(repliesViewModel.fetchReplies(post: self.post)) { post in
                        PostCell(post: post)
                            .padding(.horizontal)
                            .padding(.top, 10)
                    }
                }
            }

The replies are populating the view but its calling the function repeatedly even after leaving view. I have the Date object there so that I can see it firing.

Body:
There is a lot wrong with your code.

Your fetchReplies() function calls the async getDocuments(completion:) function. getDocuments(completion:) won't finish until after your fetchReplies() has returned, so you can't have fetchReplies() return a result. You need to make fetchReplies() take a completion handler. Something like this:

func fetchReplies(post: Post, completion: (Post) -> Void){
    let query = COLLECTION_POSTS.document(post.id).collection("post-replies")
        .order(by: "timestamp", descending: true)

    query.getDocuments { snapshot, _ in

        guard let documents = snapshot?.documents else { return }
        completion(documents.map({ Post(dictionary: $0.data()) })
        )
    }
    print(DateInterval())
}

You call fetchReplies() in a ForEach, which must return a View synchronously. You can't do that. For one thing, it will call fetchReplies repeatedly. For another, fetchReplies() is (or should be) an async function, so it can't return it's results synchronously like it needs to in order to create a View.

I guess you will need to build your Views empty, and then install your data into them once fetchReplies() function's completion handler fires. (I'm not very experienced with SwiftUI.)


问:
Angular getting BehaviorSubject value error: Property 'access_token' does not exist on type 'never'
In my Angular project I have authentication methods in the auth.service
I am storing the admin access token I got from the API in a BehaviorSubject

```<code>adminData = new BehaviorSubject(null);

saveAdminData(token:any) {
    let admin:any = new AdminData(token);
    this.adminData.next(admin);
}
</code>```

There is a function that I need to access the access_token of the admin so I tried this

```<code>this.adminData.value.access_token;
</code>```

But it gives me this error Object is possibly 'null' so I tried this

```<code>this.adminData.value!.access_token;
</code>```

But I have different error Property 'access_token' does not exist on type 'never'.

答:
You could use an ReplaySubject which behaves like a BehaviorSubject, but you don't need an initial value.</p>
```<code>adminData = new ReplaySubject<any | null>();
</code>```

Body:
In my Angular project I have authentication methods in the auth.service
I am storing the admin access token I got from the API in a BehaviorSubject

adminData = new BehaviorSubject(null);

saveAdminData(token:any) {
    let admin:any = new AdminData(token);
    this.adminData.next(admin);
}

There is a function that I need to access the access_token of the admin so I tried this

this.adminData.value.access_token;

But it gives me this error Object is possibly 'null' so I tried this

this.adminData.value!.access_token;

But I have different error Property 'access_token' does not exist on type 'never'.

Body:
You could use an ReplaySubject which behaves like a BehaviorSubject, but you don't need an initial value.

adminData = new ReplaySubject<any | null>();


问:
Attempted import error: 'Jumbotron is not exported from 'react-bootstrap' (imported as 'Jumbo')
I'm getting started learning React and trying to create a Jumbotron element from react-bootstrap. I'm pretty sure I've installed all the correct modules with npm install react-bootstrap bootstrap, but I'm getting a console error that says "Attempted import error: 'Jumbotron is not exported from 'react-bootstrap' (imported as 'Jumbo')". My code is as below:

import React from 'react';
import { Jumbotron as Jumbo, Container } from 'react-bootstrap';
import styled from 'styled-components';
import boatImage from '../assets/boatImage.jpg';

const Styles = styled.div `
  .jumbo {
    background: url(${boatImage}) no-repeat fixed bottom;
    background-size: cover;
    color: #efefef;
    height: 200px;
    position: relative;
    z-index: -2;
  }
  .overlay {
    background-color: #000;
    opacity: 0.6;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: -1;
  }
`;

export const Jumbotron = () => (

)```
</div>
</div>
</p>
<p>And here is my package.json:</p>
```{
  "name": "landing-page",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^5.0.2",
    "husky": "^7.0.1",
    "lint-staged": "^11.1.1",
    "prettier": "^2.3.2",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0-beta.4",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.0",
    "web-vitals": "^1.1.2"
  },
  "lint-staged": {
    "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
      "prettier --write"
    ]
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "devDependencies": {
    "@babel/core": "^7.14.8"
  }
}

```

Am I importing it wrong somehow? Or is there some dependency issue? Everything else from react-bootstrap appears to be working properly. Thanks in advance.

答:
I know that my response maybe late for you but it would help other people...
you can use its className instead of its component in the new version of bootstrap

.....

```

Body:
I'm getting started learning React and trying to create a Jumbotron element from react-bootstrap. I'm pretty sure I've installed all the correct modules with npm install react-bootstrap bootstrap, but I'm getting a console error that says "Attempted import error: 'Jumbotron is not exported from 'react-bootstrap' (imported as 'Jumbo')". My code is as below:

import React from 'react';
import { Jumbotron as Jumbo, Container } from 'react-bootstrap';
import styled from 'styled-components';
import boatImage from '../assets/boatImage.jpg';

const Styles = styled.div `
  .jumbo {
    background: url(${boatImage}) no-repeat fixed bottom;
    background-size: cover;
    color: #efefef;
    height: 200px;
    position: relative;
    z-index: -2;
  }
  .overlay {
    background-color: #000;
    opacity: 0.6;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: -1;
  }
`;

export const Jumbotron = () => (

)

And here is my package.json:

{
  "name": "landing-page",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^5.0.2",
    "husky": "^7.0.1",
    "lint-staged": "^11.1.1",
    "prettier": "^2.3.2",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0-beta.4",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "styled-components": "^5.3.0",
    "web-vitals": "^1.1.2"
  },
  "lint-staged": {
    "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
      "prettier --write"
    ]
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "devDependencies": {
    "@babel/core": "^7.14.8"
  }
}

Am I importing it wrong somehow? Or is there some dependency issue? Everything else from react-bootstrap appears to be working properly. Thanks in advance.

Body:
I know that my response maybe late for you but it would help other people...
you can use its className instead of its component in the new version of bootstrap

<div className="jumbotron">.....</div>


问:
How can I remove all items from the cart in PHP?
I already have some items in the cart. I want to remove them all. So, I've created a submit button with post method called 'remove_all', following doesn't work, it says "The requested URL was not found on this server." Can please someone help me?

```<code><?php
    if (isset($_POST['remove_all'])){
            unset($_SESSION['cart']);
            echo "<script>window.location = 'cart.php'</script>";
        }
?>
</code>```

And here what I wrote in my index.php

```<code><form action="remove_all" method="post" class="cart-items">
<button type="submit" value="Очистить всё" name="remove_all" class="btn btn-danger mx-2">Очистить всё</button>
</form>
</code>```

答:
It looks like you you not linking properly to your remove_all.php file. Try this:

```<code><form action="/remove_all.php" method="post" class="cart-items">
<button type="submit" value="Очистить всё" name="remove_all" class="btn btn-danger mx-2">Очистить всё</button>
</form>
</code>```

Also in your PHP file, you do not need to mix PHP and js - simply change header as following:

```<code><?php
    if (isset($_POST['remove_all'])){
            unset($_SESSION['cart']);
            // echo "<script>window.location = 'cart.php'</script>";
            header("Location: cart.php");
        }
?>
</code>```

Body:
I already have some items in the cart. I want to remove them all. So, I've created a submit button with post method called 'remove_all', following doesn't work, it says "The requested URL was not found on this server." Can please someone help me?

<?php
    if (isset($_POST['remove_all'])){
            unset($_SESSION['cart']);
            echo "";
        }
?>

And here what I wrote in my index.php

<form action="remove_all" method="post" class="cart-items">
<button type="submit" value="Очистить всё" name="remove_all" class="btn btn-danger mx-2">Очистить всё</button>
</form>

Body:
It looks like you you not linking properly to your remove_all.php file. Try this:

<form action="/remove_all.php" method="post" class="cart-items">
<button type="submit" value="Очистить всё" name="remove_all" class="btn btn-danger mx-2">Очистить всё</button>
</form>

Also in your PHP file, you do not need to mix PHP and js - simply change header as following:

<?php
    if (isset($_POST['remove_all'])){
            unset($_SESSION['cart']);
            // echo "<script>window.location = 'cart.php'</script>";
            header("Location: cart.php");
        }
?>


问:
My sprite cover the edges of other sprite Unity 2D
I'm working on a procedural world generation in Unity 2D. But when It spawns my blocks, blocks cover each other. What could be the possible problem? How can I fix it?

Thanks for your help.

Screenshot:
screenshot

答:
It might be because you made the boxcollider2D on your blocks a little too small.
Try to fit the collider perfectly with the edges of the block</p>


问:
How can I generate a secret key with validity period?
I'm working on securing vehicle to vehicle communication.
My scenario is as follows:
vehicles generate secret keys using hash chain
uses the keys to authenticate the messages
Each message is sign with a new key, and send the message with the key
So, I'm looking for a way to assign a lifetime to each key.</p>

答:
A hash function certifies that certain information has not been modified (it does not matter whether the information is encrypted or not):

```<code>hash = hash_function( DATA )
</code>```

Anyone who knows the information (DATA) can generate the hash, so a secret key is added:

```<code>hash_sign = hash_function( DATA + secret_key )
</code>```

To set an expiration value, we can add any information (the creation or expiration date depending on who controls the setting of when it expires):

```<code>hash_key = hash_function ( DATA + timestamp + secret_key )
</code>```

To sign a certain message (DATA) with expiration (timestamp) you must deliver three values:

```<code>{
    data: "DATA",
    timestamp: "2022-02-06T18:18:02.456Z",
    hash: "base64hashkey"
}
</code>```

To validate the message, you only need to know the secret key and calculate the hash, if someone tries to modify the timestamp field then the hash will not match.

This is basically what JWT does (see RFC 7519)

Body:
A hash function certifies that certain information has not been modified (it does not matter whether the information is encrypted or not):

hash = hash_function( DATA )

Anyone who knows the information (DATA) can generate the hash, so a secret key is added:

hash_sign = hash_function( DATA + secret_key )

To set an expiration value, we can add any information (the creation or expiration date depending on who controls the setting of when it expires):

hash_key = hash_function ( DATA + timestamp + secret_key )

To sign a certain message (DATA) with expiration (timestamp) you must deliver three values:

{
    data: "DATA",
    timestamp: "2022-02-06T18:18:02.456Z",
    hash: "base64hashkey"
}

To validate the message, you only need to know the secret key and calculate the hash, if someone tries to modify the timestamp field then the hash will not match.

This is basically what JWT does (see RFC 7519)


问:
Design issue when navigating side menu hamburger icon in css
My side menu is open all the time, when it is open, I show close button but the button is not proper.

The same occurs when my side menu is close which in turn shows the hamburger icon, that button is also not proper.

There are three lines for a hamburger icon, the middle one gets misaligned.

Refer code below:
Icon transition issue

    const menuBtn = document.querySelector('.menu-btn');
    let menuOpen = false;
    menuBtn.addEventListener('click', () => {
      if(!menuOpen) {
        menuBtn.classList.add('open');
        menuOpen = true;
      } else {
        menuBtn.classList.remove('open');
        menuOpen = false;
      }
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      background: #272727;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
    }
    .menu-btn {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80px;
      height: 80px;
      cursor: pointer;
      transition: all .5s ease-in-out;
      transform: translateX(0px);
      content: '';
      /* border: 3px solid #fff; */
    }
    .menu-btn__burger {
      width: 50px;
      height: 6px;
      background: #fff;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(255,101,47,.2);
      transition: all .5s ease-in-out;
    }
    .menu-btn__burger::before,
    .menu-btn__burger::after {
      content: '';
      position: absolute;
      width: 50px;
      height: 6px;
      background: #fff;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(255,101,47,.2);
      transition: all .5s ease-in-out;
     transform: translateX(-50px);
    }
    .menu-btn__burger::before {
      transform: rotate(45deg) translate(35px, -35px);
    }
    .menu-btn__burger::after {
      transform: rotate(-45deg) translate(35px, 35px);
    }
    /* ANIMATION */
    .menu-btn.open .menu-btn__burger {
      transform: translateX(0px);
      background: transparent;
      box-shadow: none;
    }
    .menu-btn.open .menu-btn__burger::before {
        transform: translateY(16px);
    }
    .menu-btn.open .menu-btn__burger::after {
        transform: translateY(-16px);
    }</code>```

<!DOCTYPE html>

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

    ```

答:
You should move the .menu-btn.open class, for more details, see the improvements I made even though it didn't change many things</p>
```<code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  background: #272727;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.menu-btn {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  cursor: pointer;
  transition: all 0.5s ease-in-out;
  transform: translateX(0px);
  content: "";
  /* border: 3px solid #fff; */
}
.menu-btn__burger {
  width: 50px;
  height: 6px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(255, 101, 47, 0.2);
  transition: all 0.5s ease-in-out;
}
.menu-btn__burger::before,
.menu-btn__burger::after {
  content: "";
  position: absolute;
  width: 50px;
  height: 6px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(255, 101, 47, 0.2);
  transition: all 0.5s ease-in-out;
  transform: translateX(-50px);
}
.menu-btn.open .menu-btn__burger::before {
  transform: rotate(45deg) translate(35px, -35px);
}
.menu-btn.open .menu-btn__burger::after {
  transform: rotate(-45deg) translate(35px, 35px);
  position: absolute;
}
/* ANIMATION */
.menu-btn.open .menu-btn__burger {
  background: transparent;
  box-shadow: none;
}
.menu-btn__burger::before {
  transform: translateY(16px);
}
.menu-btn__burger::after {
  transform: translateY(-16px);
}
</code>```

Body:
My side menu is open all the time, when it is open, I show close button but the button is not proper.

The same occurs when my side menu is close which in turn shows the hamburger icon, that button is also not proper.

There are three lines for a hamburger icon, the middle one gets misaligned.

Refer code below:
Icon transition issue

    const menuBtn = document.querySelector('.menu-btn');
    let menuOpen = false;
    menuBtn.addEventListener('click', () => {
      if(!menuOpen) {
        menuBtn.classList.add('open');
        menuOpen = true;
      } else {
        menuBtn.classList.remove('open');
        menuOpen = false;
      }
    });

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      background: #272727;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
    }
    .menu-btn {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80px;
      height: 80px;
      cursor: pointer;
      transition: all .5s ease-in-out;
      transform: translateX(0px);
      content: '';
      /* border: 3px solid #fff; */
    }
    .menu-btn__burger {
      width: 50px;
      height: 6px;
      background: #fff;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(255,101,47,.2);
      transition: all .5s ease-in-out;
    }
    .menu-btn__burger::before,
    .menu-btn__burger::after {
      content: '';
      position: absolute;
      width: 50px;
      height: 6px;
      background: #fff;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(255,101,47,.2);
      transition: all .5s ease-in-out;
     transform: translateX(-50px);
    }
    .menu-btn__burger::before {
      transform: rotate(45deg) translate(35px, -35px);
    }
    .menu-btn__burger::after {
      transform: rotate(-45deg) translate(35px, 35px);
    }
    /* ANIMATION */
    .menu-btn.open .menu-btn__burger {
      transform: translateX(0px);
      background: transparent;
      box-shadow: none;
    }
    .menu-btn.open .menu-btn__burger::before {
        transform: translateY(16px);
    }
    .menu-btn.open .menu-btn__burger::after {
        transform: translateY(-16px);
    }

<!DOCTYPE html>

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

Body:
You should move the .menu-btn.open class, for more details, see the improvements I made even though it didn't change many things

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  background: #272727;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.menu-btn {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  cursor: pointer;
  transition: all 0.5s ease-in-out;
  transform: translateX(0px);
  content: "";
  /* border: 3px solid #fff; */
}
.menu-btn__burger {
  width: 50px;
  height: 6px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(255, 101, 47, 0.2);
  transition: all 0.5s ease-in-out;
}
.menu-btn__burger::before,
.menu-btn__burger::after {
  content: "";
  position: absolute;
  width: 50px;
  height: 6px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(255, 101, 47, 0.2);
  transition: all 0.5s ease-in-out;
  transform: translateX(-50px);
}
.menu-btn.open .menu-btn__burger::before {
  transform: rotate(45deg) translate(35px, -35px);
}
.menu-btn.open .menu-btn__burger::after {
  transform: rotate(-45deg) translate(35px, 35px);
  position: absolute;
}
/* ANIMATION */
.menu-btn.open .menu-btn__burger {
  background: transparent;
  box-shadow: none;
}
.menu-btn__burger::before {
  transform: translateY(16px);
}
.menu-btn__burger::after {
  transform: translateY(-16px);
}


问:
Getting information from mysql using jquery
i have mysql database for i fetch information using json
for example:

```<code>$sql ="SELECT * FROM parent WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
 {
$abc=$row[id];
}
echo json_encode($abc)
</code>```

Now how can i display this json encoded element in my main html file using jquery?
what i want to do is based on this fetched element i want to do some if else operation.

for example:

```<code>if(value of row[id](should be achieved using jquery) ==null)
{}
else
{}
</code>```

I am looking for something like $(xxxx).somefunction()
Thanks in advance.

答:
You can create a javascript var:

```<code>echo('var test = ' . json_encode($abc));
</code>```

Now you can acces the var "test" with javascript.

Body:
i have mysql database for i fetch information using json
for example:

$sql ="SELECT * FROM parent WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
 {
$abc=$row[id];
}
echo json_encode($abc)

Now how can i display this json encoded element in my main html file using jquery?
what i want to do is based on this fetched element i want to do some if else operation.

for example:

if(value of row[id](should be achieved using jquery) ==null)
{}
else
{}

I am looking for something like $(xxxx).somefunction()
Thanks in advance.

Body:
You can create a javascript var:

echo('var test = ' . json_encode($abc));

Now you can acces the var "test" with javascript.


问:
How to get the every week by google spread sheet
I want to have date of every weeks.

I put 07/02/2022 in F5 cell and put =EDATE(F5 + 7) in G5 cell

But N/A comes in G5

I guess maybe I put 07/02/2022 in F5 in a wrong way..

What should I do?

答:
The date of the next week starting on any day

```<code>function nextWeekDateStartingOnThis(day = 1) {//Sun(0) - Sat(6)
  let dt = new Date();
  let nd = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + 7 - dt.getDay() + day);
  Logger.log(nd);
  return nd;//this returns the date of the next monday because day = 1
}
</code>```

If you want the date of the next tuesday then make day = 2

Body:
The date of the next week starting on any day

function nextWeekDateStartingOnThis(day = 1) {//Sun(0) - Sat(6)
  let dt = new Date();
  let nd = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + 7 - dt.getDay() + day);
  Logger.log(nd);
  return nd;//this returns the date of the next monday because day = 1
}

If you want the date of the next tuesday then make day = 2


问:
woocommerce product shortcodes template
As I know

[products limit=”4″ columns=”4″ on_sale=”true” ] will show all on sale products,

[products limit=”3″ columns=”3″ best_selling=”true” ] will show best selling products,

If I were not wrong, both of the shortcodes would call the content-product.php file to display the products.

My question is how can I make different product shortcodes call different php template files to show the related products instead of calling the same file that is content-product.php?

For example,

on sale shortcodes call content-product-1.php

best selling shortcodes call content-product-2.php

Thank you!

答:
Create our own shortcode to display the specific products and our our own template as below,
for example, wc_get_template_part( 'content', 'product-test' );</p>
```<code>add_shortcode( 'sale_products_test', 'sale_products' );
function sale_products( $atts ){
    global $woocommerce_loop, $woocommerce;

    extract( shortcode_atts( array(
        'per_page'      => '12',
        'columns'       => '3',
        'orderby'       => 'title',
        'category'      => 'clearance',
        'order'         => 'asc'
        ), $atts ) );

    // Get products on sale
    $product_ids_on_sale = woocommerce_get_product_ids_on_sale();

    $meta_query = array();
    $meta_query[] = $woocommerce->query->visibility_meta_query();
    $meta_query[] = $woocommerce->query->stock_status_meta_query();

    $args = array(
        'posts_per_page'=> $per_page,
        'orderby'       => $orderby,
        'order'         => $order,
        'no_found_rows' => 1,
        'post_status'   => 'publish',
        'post_type'     => 'product',
        'orderby'       => 'date',
        'order'         => 'ASC',
        'meta_query'    => $meta_query,
        'post__in'      => $product_ids_on_sale,
        'tax_query' => array( array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => $category,
        )),
    );

    ob_start();

    $products = new WP_Query( $args );

    $woocommerce_loop['columns'] = $columns;

    if ( $products->have_posts() ) : ?>

        <?php woocommerce_product_loop_start(); ?>

            <?php while ( $products->have_posts() ) : $products->the_post(); ?>

                <?php wc_get_template_part( 'content', 'product-test' ); ?>

            <?php endwhile; // end of the loop. ?>

        <?php woocommerce_product_loop_end(); ?>

    <?php endif;

    wp_reset_postdata();

    return ob_get_clean();
}
</code>```

Title: woocommerce product shortcodes template

Body:
Create our own shortcode to display the specific products and our our own template as below,
for example, wc_get_template_part( 'content', 'product-test' );

add_shortcode( 'sale_products_test', 'sale_products' );
function sale_products( $atts ){
    global $woocommerce_loop, $woocommerce;

    extract( shortcode_atts( array(
        'per_page'      => '12',
        'columns'       => '3',
        'orderby'       => 'title',
        'category'      => 'clearance',
        'order'         => 'asc'
        ), $atts ) );

    // Get products on sale
    $product_ids_on_sale = woocommerce_get_product_ids_on_sale();

    $meta_query = array();
    $meta_query[] = $woocommerce->query->visibility_meta_query();
    $meta_query[] = $woocommerce->query->stock_status_meta_query();

    $args = array(
        'posts_per_page'=> $per_page,
        'orderby'       => $orderby,
        'order'         => $order,
        'no_found_rows' => 1,
        'post_status'   => 'publish',
        'post_type'     => 'product',
        'orderby'       => 'date',
        'order'         => 'ASC',
        'meta_query'    => $meta_query,
        'post__in'      => $product_ids_on_sale,
        'tax_query' => array( array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => $category,
        )),
    );

    ob_start();

    $products = new WP_Query( $args );

    $woocommerce_loop['columns'] = $columns;

    if ( $products->have_posts() ) : ?>

        <?php woocommerce_product_loop_start(); ?>

            <?php while ( $products->have_posts() ) : $products->the_post(); ?>

                <?php wc_get_template_part( 'content', 'product-test' ); ?>

            <?php endwhile; // end of the loop. ?>

        <?php woocommerce_product_loop_end(); ?>

    <?php endif;

    wp_reset_postdata();

    return ob_get_clean();
}


问:
XAML small Multicolumn List inside LiesView Element
In my Xamarin App I have a ListView, inside the ItemTemplate I have to show a text-only list with 3 columns.

The first idea was to use a GroupedListView, but in this case all subentries are selectable separately.
That is not what I want. The ListView Item should appear as one selectable element.

The Second idea I found on my research is to add Gridview rows by code, but this would break my MVVM concept. I need a solution which works with databinding only.

The third thing I sometimes read is: cascade a ListView inside the ListView. But mostly the answer to such idea is: "never do this".

Any other idea what I can do for this?
What I want is something like this:

```<code>ListView Entry 1
     04:13      Jhonny           3,24$
     09:45      Some Long Nam... 8,23$
     14:42      Mike             5,45$
----------------------------------------
ListView Entry 2
     07:13      Jhonny           3,24$
     11:22      Some Long Nam... 8,23$
     18:42      Mike             5,45$
----------------------------------------
ListView Entry 3
     05:13      Jhonny           3,24$
     15:45      Some Long Nam... 8,23$
     19:42      Mike             5,45$
----------------------------------------
</code>```

Always the whole Listview Entry should be selectable as one element.

答:
Guess you could use the BindableLayout. You didn't specify the Type, so i made a dummy type.
View:

```<code><CollectionView ItemsSource="{Binding GroupItems}" SelectionMode="Single">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout Orientation="Vertical" Margin="5">
                <Label Text="{Binding Title}"/>
                <StackLayout BindableLayout.ItemsSource="{Binding Entries}">
                    <BindableLayout.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <Label Text="{Binding Time}" HorizontalTextAlignment="Center"/>
                                <Label Text="{Binding Name}" Grid.Column="1" LineBreakMode="TailTruncation"/>
                                <Label Text="{Binding Amount}" Grid.Column="2" HorizontalTextAlignment="Center"/>
                            </Grid>
                        </DataTemplate>
                    </BindableLayout.ItemTemplate>

                </StackLayout>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>
</code>```

Codebehind:

```<code> public ObservableCollection<GroupItem> GroupItems { get; set; } = new ObservableCollection<GroupItem>();
    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
        GroupItem item1 = new GroupItem();
        item1.Title = "Entry 1";
        item1.Entries.Add(new Entry { Time = "10:13", Name = "Johnny", Amount = "10,24$" });
        item1.Entries.Add(new Entry { Time = "12:11", Name = "Some long name that will be truncated", Amount = "20,14$" });
        item1.Entries.Add(new Entry { Time = "10:13", Name = "Mike", Amount = "14,27$" });
        GroupItems.Add(item1);

        GroupItem item2 = new GroupItem();
        item2.Title = "Entry 2";
        item2.Entries.Add(new Entry { Time = "11:13", Name = "Finn", Amount = "10,24$" });
        item2.Entries.Add(new Entry { Time = "14:11", Name = "Some long name that will be truncated", Amount = "20,14$" });
        GroupItems.Add(item2);

        GroupItem item3 = new GroupItem();
        item3.Title = "Entry 3";
        item3.Entries.Add(new Entry { Time = "11:13", Name = "Finn", Amount = "10,24$" });
        item3.Entries.Add(new Entry { Time = "14:11", Name = "Some long name that will be truncated", Amount = "20,14$" });
        item3.Entries.Add(new Entry { Time = "14:11", Name = "Martin", Amount = "50,15$" });
        item3.Entries.Add(new Entry { Time = "14:11", Name = "Elon musk", Amount = "30,14$" });
        GroupItems.Add(item3);
    }

    public class GroupItem
    {
        public string Title { get; set; }
        public List<Entry> Entries { get; set; } = new List<Entry>();
    }

    public class Entry
    {
        public string Time { get; set; }
        public string Name { get; set; }
        public string Amount { get; set; }
    }
</code>```

This gives you the possibility of a dynamic amount of rows, and every group is selectable.

Result:

Body:
In my Xamarin App I have a ListView, inside the ItemTemplate I have to show a text-only list with 3 columns.

The first idea was to use a GroupedListView, but in this case all subentries are selectable separately.
That is not what I want. The ListView Item should appear as one selectable element.

The Second idea I found on my research is to add Gridview rows by code, but this would break my MVVM concept. I need a solution which works with databinding only.

The third thing I sometimes read is: cascade a ListView inside the ListView. But mostly the answer to such idea is: "never do this".

Any other idea what I can do for this?
What I want is something like this:

ListView Entry 1
     04:13      Jhonny           3,24$
     09:45      Some Long Nam... 8,23$
     14:42      Mike             5,45$
----------------------------------------
ListView Entry 2
     07:13      Jhonny           3,24$
     11:22      Some Long Nam... 8,23$
     18:42      Mike             5,45$
----------------------------------------
ListView Entry 3
     05:13      Jhonny           3,24$
     15:45      Some Long Nam... 8,23$
     19:42      Mike             5,45$
----------------------------------------

Always the whole Listview Entry should be selectable as one element.

Body:
Guess you could use the BindableLayout. You didn't specify the Type, so i made a dummy type.
View:

<CollectionView ItemsSource="{Binding GroupItems}" SelectionMode="Single">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout Orientation="Vertical" Margin="5">
                <Label Text="{Binding Title}"/>
                <StackLayout BindableLayout.ItemsSource="{Binding Entries}">
                    <BindableLayout.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <Label Text="{Binding Time}" HorizontalTextAlignment="Center"/>
                                <Label Text="{Binding Name}" Grid.Column="1" LineBreakMode="TailTruncation"/>
                                <Label Text="{Binding Amount}" Grid.Column="2" HorizontalTextAlignment="Center"/>
                            </Grid>
                        </DataTemplate>
                    </BindableLayout.ItemTemplate>

                </StackLayout>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Codebehind:

 public ObservableCollection<GroupItem> GroupItems { get; set; } = new ObservableCollection<GroupItem>();
    public MainPage()
    {
        InitializeComponent();
        BindingContext = this;
        GroupItem item1 = new GroupItem();
        item1.Title = "Entry 1";
        item1.Entries.Add(new Entry { Time = "10:13", Name = "Johnny", Amount = "10,24$" });
        item1.Entries.Add(new Entry { Time = "12:11", Name = "Some long name that will be truncated", Amount = "20,14$" });
        item1.Entries.Add(new Entry { Time = "10:13", Name = "Mike", Amount = "14,27$" });
        GroupItems.Add(item1);

        GroupItem item2 = new GroupItem();
        item2.Title = "Entry 2";
        item2.Entries.Add(new Entry { Time = "11:13", Name = "Finn", Amount = "10,24$" });
        item2.Entries.Add(new Entry { Time = "14:11", Name = "Some long name that will be truncated", Amount = "20,14$" });
        GroupItems.Add(item2);

        GroupItem item3 = new GroupItem();
        item3.Title = "Entry 3";
        item3.Entries.Add(new Entry { Time = "11:13", Name = "Finn", Amount = "10,24$" });
        item3.Entries.Add(new Entry { Time = "14:11", Name = "Some long name that will be truncated", Amount = "20,14$" });
        item3.Entries.Add(new Entry { Time = "14:11", Name = "Martin", Amount = "50,15$" });
        item3.Entries.Add(new Entry { Time = "14:11", Name = "Elon musk", Amount = "30,14$" });
        GroupItems.Add(item3);
    }

    public class GroupItem
    {
        public string Title { get; set; }
        public List<Entry> Entries { get; set; } = new List<Entry>();
    }

    public class Entry
    {
        public string Time { get; set; }
        public string Name { get; set; }
        public string Amount { get; set; }
    }

This gives you the possibility of a dynamic amount of rows, and every group is selectable.

Result:


问:
How to detect the closest value below and above a given reference variable in a data frame in R?
Consider the following random MWE.

For every row, I am trying to determine which variable has the closest value below the constant reference_day and which variable has the closest value above the constant reference_day.

```<code>df1 <-
  structure(
    list(id = 1:5,
      gender = c("female", "male", "male", "male", "male"),
      reference_day = structure(c(18052, NA, 18052, 18052, 18052), class = "Date"),
      var1 = structure(c(16505, 17144, 18139, NA, 16639), class = "Date"),
      var2 = structure(c(NA, 18042, 16544, 16697, NA), class = "Date"),
      var3 = structure(c(17845, 18070, 17152, 16571, NA), class = "Date")),
  row.names = c(NA, -5L), class = "data.frame")

df1

  id gender reference_day       var1       var2       var3
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>
</code>```

The result I'm after is this:

```<code>  id gender reference_day       var1       var2       var3 closest_to_left closest_to_right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10            var3             <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23            <NA>             <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17            var3             var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16            var2             <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>            var1             <NA>
</code>```

After much trial and error, I was actually able to find a solution to this with the case_when function of dplyr, but it took an insane amount of boilerplate code, which lead me to think that there just has to be a more clever solution.

I personally prefer to work with dplyr, but any help is greatly appreciated.

答:
Here's a relatively simple tidyverse approach. First we define a function to pick the closest match before or after the reference_day within each group, then we apply that in each case to add the two new columns. I use the side parameter to define whether we want matches on the side with negative time differences (before) or positive (after).

```<code>closest <- function(df, side = -1) {
  df %>%
    pivot_longer(-c(id:reference_day)) %>%
    group_by(id, gender) %>%
    arrange(value) %>%
    mutate(dif = (value - reference_day) * side) %>%
    filter(dif > 0) %>%
    slice_min(dif) %>%
    select(name) %>%
    ungroup()
}

df1 %>%
  left_join(df1 %>% closest(-1) %>% rename("left" = "name")) %>%
  left_join(df1 %>% closest(1) %>% rename("right" = "name"))
</code>```

Result

```<code>  id gender reference_day       var1       var2       var3 left right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10 var3  <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23 <NA>  <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17 var3  var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16 var2  <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA> var1  <NA>
</code>```

Body:
Consider the following random MWE.

For every row, I am trying to determine which variable has the closest value below the constant reference_day and which variable has the closest value above the constant reference_day.

df1 <-
  structure(
    list(id = 1:5,
      gender = c("female", "male", "male", "male", "male"),
      reference_day = structure(c(18052, NA, 18052, 18052, 18052), class = "Date"),
      var1 = structure(c(16505, 17144, 18139, NA, 16639), class = "Date"),
      var2 = structure(c(NA, 18042, 16544, 16697, NA), class = "Date"),
      var3 = structure(c(17845, 18070, 17152, 16571, NA), class = "Date")),
  row.names = c(NA, -5L), class = "data.frame")

df1

  id gender reference_day       var1       var2       var3
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>

The result I'm after is this:

  id gender reference_day       var1       var2       var3 closest_to_left closest_to_right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10            var3             <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23            <NA>             <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17            var3             var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16            var2             <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA>            var1             <NA>

After much trial and error, I was actually able to find a solution to this with the case_when function of dplyr, but it took an insane amount of boilerplate code, which lead me to think that there just has to be a more clever solution.

I personally prefer to work with dplyr, but any help is greatly appreciated.

Body:
Here's a relatively simple tidyverse approach. First we define a function to pick the closest match before or after the reference_day within each group, then we apply that in each case to add the two new columns. I use the side parameter to define whether we want matches on the side with negative time differences (before) or positive (after).

closest <- function(df, side = -1) {
  df %>%
    pivot_longer(-c(id:reference_day)) %>%
    group_by(id, gender) %>%
    arrange(value) %>%
    mutate(dif = (value - reference_day) * side) %>%
    filter(dif > 0) %>%
    slice_min(dif) %>%
    select(name) %>%
    ungroup()
}

df1 %>%
  left_join(df1 %>% closest(-1) %>% rename("left" = "name")) %>%
  left_join(df1 %>% closest(1) %>% rename("right" = "name"))

Result

  id gender reference_day       var1       var2       var3 left right
1  1 female    2019-06-05 2015-03-11       <NA> 2018-11-10 var3  <NA>
2  2   male          <NA> 2016-12-09 2019-05-26 2019-06-23 <NA>  <NA>
3  3   male    2019-06-05 2019-08-31 2015-04-19 2016-12-17 var3  var1
4  4   male    2019-06-05       <NA> 2015-09-19 2015-05-16 var2  <NA>
5  5   male    2019-06-05 2015-07-23       <NA>       <NA> var1  <NA>


问:
Approach to send a large JSON payload to a web service
Consider a small Go application that reads a large JSON file 2GB+, marshals the JSON data into a struct, and POSTs the JSON data to a web service endpoint.

The web service receiving the payload changed its functionality, and now has a limit of 25MB per payload. What would be the best approach to overcome this issue using Go? I've thought of the following, however I'm not sure it is the best approach:

Creating a function to split the large JSON file into multiple smaller ones (up to 20MB), and then iterate over the files sending multiple smaller requests.

Similar function to the one being used to currently send the entire JSON payload:

```<code>func sendDataToService(data StructData) {
    payload, err := json.Marshal(data)
    if err != nil {
        log.Println("ERROR:", err)
    }

    request, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(payload))
    if err != nil {
        log.Println("ERROR:", err)
    }

    client := &http.Client{}
    response, err := client.Do(request)
    log.Println("INFORMATIONAL:", request)
    if err != nil {
        log.Println("ERROR:", err)
    }
    defer response.Body.Close()
}
</code>```

答:
You can break the input into chunks and send each piece individually:</p>
```<code>dec := json.NewDecoder(inputStream)
tok, err := dec.Token()
if err != nil {
    return err
}
if tok == json.Delim('[') {
    for {
        var obj json.RawMessage
        if err := dec.Decode(&obj); err != nil {
            return err
        }
        // Here, obj contains one element of the array. You can send this
        // to the server.
        if !dec.More() {
            break
        }
    }
}
</code>```

Body:
Consider a small Go application that reads a large JSON file 2GB+, marshals the JSON data into a struct, and POSTs the JSON data to a web service endpoint.

The web service receiving the payload changed its functionality, and now has a limit of 25MB per payload. What would be the best approach to overcome this issue using Go? I've thought of the following, however I'm not sure it is the best approach:

Creating a function to split the large JSON file into multiple smaller ones (up to 20MB), and then iterate over the files sending multiple smaller requests.

Similar function to the one being used to currently send the entire JSON payload:

func sendDataToService(data StructData) {
    payload, err := json.Marshal(data)
    if err != nil {
        log.Println("ERROR:", err)
    }

    request, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(payload))
    if err != nil {
        log.Println("ERROR:", err)
    }

    client := &http.Client{}
    response, err := client.Do(request)
    log.Println("INFORMATIONAL:", request)
    if err != nil {
        log.Println("ERROR:", err)
    }
    defer response.Body.Close()
}

Body:
You can break the input into chunks and send each piece individually:

dec := json.NewDecoder(inputStream)
tok, err := dec.Token()
if err != nil {
    return err
}
if tok == json.Delim('[') {
    for {
        var obj json.RawMessage
        if err := dec.Decode(&obj); err != nil {
            return err
        }
        // Here, obj contains one element of the array. You can send this
        // to the server.
        if !dec.More() {
            break
        }
    }
}


问:
CSS Div overlaps text
I'm releasing a new feature on my website and I want to mark the new a-tag in the navbar with a "NEW" sign top right of the a-tag (little overlapping). But I don't know how to make this overlapping happen and that my span with "NEW" (the text) is shown in full-width. Difficult to describe for me, current status is in the picture. I tried z-index, didn't work.
Here is my code.

navbar html and css:

```<code><li class="nav-item p-1">
      <a class="nav-link" routerLink="overview/cases" routerLinkActive="active-link" (click)="collapsed=true">Cases<span class="new-feature">NEW</span></a>
    </li>

    .new-feature{
      width: 50px;
      height: 20px;
     background: linear-gradient(135deg, #9932cc, #fa490a);
      color: #fff;
      font-size: 15px;
      border-radius: 15px;
      text-align: center;
    }
</code>```

It currently looks like this:

答:
try give relative position to  or
 and absolute position to , than z-index will be working

```<code>   <li class="nav-item p-1" style="position:relative;">
    <a class="nav-link" routerLink="overview/cases" routerLinkActive="active-link" (click)="collapsed=true">Cases
     <span class="new-feature" style="position:absolute;top:0;left:0;">NEW</span>
    </a>
   </li>
</code>```

Title: CSS Div overlaps text

Body:
I'm releasing a new feature on my website and I want to mark the new a-tag in the navbar with a "NEW" sign top right of the a-tag (little overlapping). But I don't know how to make this overlapping happen and that my span with "NEW" (the text) is shown in full-width. Difficult to describe for me, current status is in the picture. I tried z-index, didn't work.
Here is my code.

navbar html and css:

      CasesNEW

    .new-feature{
      width: 50px;
      height: 20px;
     background: linear-gradient(135deg, #9932cc, #fa490a);
      color: #fff;
      font-size: 15px;
      border-radius: 15px;
      text-align: center;
    }

It currently looks like this:

Body:
try give relative position to <a> or <li> and absolute position to <span>, than z-index will be working

   <li class="nav-item p-1" style="position:relative;">
    <a class="nav-link" routerLink="overview/cases" routerLinkActive="active-link" (click)="collapsed=true">Cases
     <span class="new-feature" style="position:absolute;top:0;left:0;">NEW</span>
    </a>
   </li>


问:
Using e.printStackTrace() in Java
This is probably a newbie question, but hope you can help me. :) I have something like this:

```<code>try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}
</code>```

I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line.  When I press Alt+Enter, it says Throwable.printStackTrace() should be removed.  What does this mean?  Could anyone give more insight as what this may mean? Or can I ignore this?

Thanks!

答:
Try:</p>

```<code>e.printStackTrace(System.out);
</code>```

Title: Using e.printStackTrace() in Java

Body:
This is probably a newbie question, but hope you can help me. :) I have something like this:

try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}

I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line.  When I press Alt+Enter, it says Throwable.printStackTrace() should be removed.  What does this mean?  Could anyone give more insight as what this may mean? Or can I ignore this?

Thanks!

Body:
Try:

e.printStackTrace(System.out);


问:
How to limit (Flutter) string min/max length with security rules in Firebase
I'm using Firestore Database and I'm now trying to add security rules after building many of the pages without security rules.  That was definitely a huge mistake.  I have reviewed a lot of the documentation and watched a bunch of the Firebase security rules videos which are all clear but as a beginner I still need guidance.  I have also reviewed SO threads which have helped get me to this point.

My goal is to have client side validation and server side validation that requires a minimum of 3 characters and allows a maximum of 20 characters when a user creates a new account and adds their userName.  And the same rules should apply when they update their userName.  Here is an image of the database.

My security rules are:

```<code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
    allow read, write, update: if request.auth != null
    && request.auth.uid == userId
    && resource.data.username.length >= 3
    && resource.data.username.length <= 30
    && resource.data.undername is string;
    }
</code>```

In the Rules Playground I get an error message:

Error running simulation — Error: simulator.rules line [10], column [28]. Null value error.

And in the console I get a similar error message:

Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

I can't figure out where I am going wrong with my rules code.  Any help would be greatly appreciated.  Thanks

答:
You must be checking request.resource.data which contains incoming data and not resource.data which holds existing data from the document. Also try using size() instead of .length to check string length:

```<code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write, update: if request.auth != null
        && request.auth.uid == userId
        && request.resource.data.username.size() >= 3
        && request.resource.data.username.size() <= 30
        && request.resource.data.undername is string;
    }
  }
}
</code>```

For example, if current value of username is 'Jim' in the document and you are trying to update it to 'James', value of resource.data.username.size() would be 3 (length of existing name) and request.resource.data.username.size() would be 5 (length of new name). It's length of the new name that you are supposed to measure so you need to use request.resource.

Body:
I'm using Firestore Database and I'm now trying to add security rules after building many of the pages without security rules.  That was definitely a huge mistake.  I have reviewed a lot of the documentation and watched a bunch of the Firebase security rules videos which are all clear but as a beginner I still need guidance.  I have also reviewed SO threads which have helped get me to this point.

My goal is to have client side validation and server side validation that requires a minimum of 3 characters and allows a maximum of 20 characters when a user creates a new account and adds their userName.  And the same rules should apply when they update their userName.  Here is an image of the database.

My security rules are:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
    allow read, write, update: if request.auth != null
    && request.auth.uid == userId
    && resource.data.username.length >= 3
    && resource.data.username.length <= 30
    && resource.data.undername is string;
    }

In the Rules Playground I get an error message:

Error running simulation — Error: simulator.rules line [10], column [28]. Null value error.

And in the console I get a similar error message:

Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

I can't figure out where I am going wrong with my rules code.  Any help would be greatly appreciated.  Thanks

Body:
You must be checking request.resource.data which contains incoming data and not resource.data which holds existing data from the document. Also try using size() instead of .length to check string length:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write, update: if request.auth != null
        && request.auth.uid == userId
        && request.resource.data.username.size() >= 3
        && request.resource.data.username.size() <= 30
        && request.resource.data.undername is string;
    }
  }
}

For example, if current value of username is 'Jim' in the document and you are trying to update it to 'James', value of resource.data.username.size() would be 3 (length of existing name) and request.resource.data.username.size() would be 5 (length of new name). It's length of the new name that you are supposed to measure so you need to use request.resource.


问:
simplification of function signature in Java
I want to "simplify" the signature of functions, but I'm not sure if this action is possible. If anyone can help me I will be very grateful.

Could anyone help me how to transfer the code from this:

(In the main Main class I wrote the lines below)

```<code>Tree tree = new Tree(15);

        int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
        int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};

        for (int i = 0; i < set1.length; i++) {
            tree.add(tree, set1[i]);
        }

        System.out.println("The depth of the tree is " + tree.depth(tree) + ".");
</code>```

I want to remove the input (Tree tree) for the functions of the Tree class, if this action is possible:

```<code>Tree tree = new Tree(15);

        int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
        int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};

        for (int i = 0; i < set1.length; i++) {
            tree.add(set1[i]);
        }

        System.out.println("The depth of the tree is " + tree.depth() + ".");
</code>```

Tree class:

```<code>public class Tree {

    /**
     * The value of this node in the tree.
     */
    public int node;

    /**
     * The left subtree.
     */
    private Tree lhs;

    /**
     * The right subtree.
     */
    private Tree rhs;

    /**
     * Creates a new tree with the value node.
     * @param node The value of this node in the tree.
     */
    public Tree(int node) {
        this.node = node;
        this.lhs = null;
        this.rhs = null;

    }

 public void add(Tree tree, int insert) {
        addRecursive(tree, insert);
    }

    private Tree addRecursive(Tree current, int value) {
        if (current == null) {
            return new Tree(value);
        }

        if (value < current.node) {
            current.lhs = addRecursive(current.lhs, value);
        } else if (value > current.node) {
            current.rhs = addRecursive(current.rhs, value);
        } else {
            // value already exists
            return current;
        }

        return current;
    }

public int depth(Tree tree) {
        // Root being null means tree doesn't exist.
        if (tree == null)
            return 0;

        // Get the depth of the left and right subtree
        // using recursion.
        int leftDepth = depth(tree.lhs);
        int rightDepth = depth(tree.rhs);

        // Choose the larger one and add the root to it.
        if (leftDepth > rightDepth)
            return (leftDepth + 1);
        else
            return (rightDepth + 1);
    }

}

</code>```

答:
You just need to use this as a reference to the curent object.

```<code> public void add(int insert) {
    addRecursive(this, insert);
}
</code>```

Also in Depth() you can do as following:

```<code>public int depth() => depth(this);

private int depth(Tree tree) {
    // Root being null means tree doesn't exist.
    if (tree == null)
        return 0;

    // Get the depth of the left and right subtree
    // using recursion.
    int leftDepth = depth(tree.lhs);
    int rightDepth = depth(tree.rhs);

    // Choose the larger one and add the root to it.
    if (leftDepth > rightDepth)
        return (leftDepth + 1);
    else
        return (rightDepth + 1);
}
</code>```

}

Body:
I want to "simplify" the signature of functions, but I'm not sure if this action is possible. If anyone can help me I will be very grateful.

Could anyone help me how to transfer the code from this:

(In the main Main class I wrote the lines below)

Tree tree = new Tree(15);

        int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
        int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};

        for (int i = 0; i < set1.length; i++) {
            tree.add(tree, set1[i]);
        }

        System.out.println("The depth of the tree is " + tree.depth(tree) + ".");

I want to remove the input (Tree tree) for the functions of the Tree class, if this action is possible:

Tree tree = new Tree(15);

        int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
        int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};

        for (int i = 0; i < set1.length; i++) {
            tree.add(set1[i]);
        }

        System.out.println("The depth of the tree is " + tree.depth() + ".");

Tree class:

public class Tree {

    /**
     * The value of this node in the tree.
     */
    public int node;

    /**
     * The left subtree.
     */
    private Tree lhs;

    /**
     * The right subtree.
     */
    private Tree rhs;

    /**
     * Creates a new tree with the value node.
     * @param node The value of this node in the tree.
     */
    public Tree(int node) {
        this.node = node;
        this.lhs = null;
        this.rhs = null;

    }

 public void add(Tree tree, int insert) {
        addRecursive(tree, insert);
    }

    private Tree addRecursive(Tree current, int value) {
        if (current == null) {
            return new Tree(value);
        }

        if (value < current.node) {
            current.lhs = addRecursive(current.lhs, value);
        } else if (value > current.node) {
            current.rhs = addRecursive(current.rhs, value);
        } else {
            // value already exists
            return current;
        }

        return current;
    }

public int depth(Tree tree) {
        // Root being null means tree doesn't exist.
        if (tree == null)
            return 0;

        // Get the depth of the left and right subtree
        // using recursion.
        int leftDepth = depth(tree.lhs);
        int rightDepth = depth(tree.rhs);

        // Choose the larger one and add the root to it.
        if (leftDepth > rightDepth)
            return (leftDepth + 1);
        else
            return (rightDepth + 1);
    }

}

Body:
You just need to use this as a reference to the curent object.

 public void add(int insert) {
    addRecursive(this, insert);
}

Also in Depth() you can do as following:

public int depth() => depth(this);

private int depth(Tree tree) {
    // Root being null means tree doesn't exist.
    if (tree == null)
        return 0;

    // Get the depth of the left and right subtree
    // using recursion.
    int leftDepth = depth(tree.lhs);
    int rightDepth = depth(tree.rhs);

    // Choose the larger one and add the root to it.
    if (leftDepth > rightDepth)
        return (leftDepth + 1);
    else
        return (rightDepth + 1);
}

}


问:
Flutter Riverpod does not call function
I'm starting with Flutter and I chose Riverpod to manage my state. I created a StateNotifier that has two functions, one setSelected that chooses the item in the menu and the other getSelected that checks who was selected and changes the colors. The first works on click but the second only works when starting the page.

Below are my classes:

1- MenuNotifier

```<code>class MenuNotifier extends StateNotifier<CategoryModel> {
  MenuNotifier() : super(menuItem);

  static CategoryModel menuItem = CategoryModel.allCategories.first;

  void setSelected(CategoryModel item) {
    menuItem = item;
    print(menuItem.id);
  }

  bool getSelected(CategoryModel item) {
    return menuItem.id == item.id ? true : false;
  }
}
</code>```

2 - MenuCategoryComponent

```<code>final menuProvider = StateNotifierProvider<MenuNotifier, CategoryModel>((ref) {
  return MenuNotifier();
});

class MenuCategoryComponent extends ConsumerWidget {
  List<CategoryModel> allCategories = CategoryModel.allCategories;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Container(
      color: uiColor.second,
      child: ListView.builder(
          itemCount: allCategories.length,
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Consumer(builder: (context, ref, _) {
              final _menuItem = ref.watch(menuProvider.notifier);
              return Container(
                color: ref
                        .read(menuProvider.notifier)
                        .getSelected(allCategories[index])
                    ? uiColor.comp_1
                    : uiColor.second,
                child: TextButton(
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.zero,
                    alignment: Alignment.center,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Text(allCategories[index].label!,
                        style: uiTextStyle.text1),
                  ),
                  onPressed: () {
                    ref
                        .read(menuProvider.notifier)
                        .setSelected(allCategories[index]);
                  },
                ),
              );
            });
          }),
    );
  }
}
</code>```

As you can see I have a Container that should change color with a condition that returns a boolean if the selected item is the same as the current one in the ListView. And I use read from Riverpod.

答:
I think the problem is you are watching the .notifier instead of listening to its changes, by the docs:

Obtains the [StateNotifier] associated with this
[StateNotifierProvider], without listening to it.

Listening to this provider may cause providers/widgets to rebuild in
the event that the [StateNotifier] it recreated.

So if you want to listen to changes you should use ref.watch(menuProvider). Also as a tip you could use select to filter that value:

```<code>/// No reason to be ConsumerWidget because you're using a Consumer inside
class MenuCategoryComponent extends StatelessWidget {
  List<CategoryModel> allCategories = CategoryModel.allCategories;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: uiColor.second,
      child: ListView.builder(
          itemCount: allCategories.length,
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Consumer(builder: (context, ref, _) {
              final isSelected = ref.watch(menuProvider.select((v) => v.getSelected(allCategories[index])));
              return Container(
                color: isSelected
                    ? uiColor.comp_1
                    : uiColor.second,
                child: TextButton(
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.zero,
                    alignment: Alignment.center,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Text(allCategories[index].label!,
                        style: uiTextStyle.text1),
                  ),
                  onPressed: () {
                    ref
                        .read(menuProvider.notifier)
                        .setSelected(allCategories[index]);
                  },
                ),
              );
            });
          }
       ),
    );
  }
}
</code>```

Title: Flutter Riverpod does not call function

Body:
I'm starting with Flutter and I chose Riverpod to manage my state. I created a StateNotifier that has two functions, one setSelected that chooses the item in the menu and the other getSelected that checks who was selected and changes the colors. The first works on click but the second only works when starting the page.

Below are my classes:

1- MenuNotifier

class MenuNotifier extends StateNotifier<CategoryModel> {
  MenuNotifier() : super(menuItem);

  static CategoryModel menuItem = CategoryModel.allCategories.first;

  void setSelected(CategoryModel item) {
    menuItem = item;
    print(menuItem.id);
  }

  bool getSelected(CategoryModel item) {
    return menuItem.id == item.id ? true : false;
  }
}

2 - MenuCategoryComponent

final menuProvider = StateNotifierProvider<MenuNotifier, CategoryModel>((ref) {
  return MenuNotifier();
});

class MenuCategoryComponent extends ConsumerWidget {
  List<CategoryModel> allCategories = CategoryModel.allCategories;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Container(
      color: uiColor.second,
      child: ListView.builder(
          itemCount: allCategories.length,
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Consumer(builder: (context, ref, _) {
              final _menuItem = ref.watch(menuProvider.notifier);
              return Container(
                color: ref
                        .read(menuProvider.notifier)
                        .getSelected(allCategories[index])
                    ? uiColor.comp_1
                    : uiColor.second,
                child: TextButton(
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.zero,
                    alignment: Alignment.center,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Text(allCategories[index].label!,
                        style: uiTextStyle.text1),
                  ),
                  onPressed: () {
                    ref
                        .read(menuProvider.notifier)
                        .setSelected(allCategories[index]);
                  },
                ),
              );
            });
          }),
    );
  }
}

As you can see I have a Container that should change color with a condition that returns a boolean if the selected item is the same as the current one in the ListView. And I use read from Riverpod.

Body:
I think the problem is you are watching the .notifier instead of listening to its changes, by the docs:

Obtains the [StateNotifier] associated with this
[StateNotifierProvider], without listening to it.

Listening to this provider may cause providers/widgets to rebuild in
the event that the [StateNotifier] it recreated.

So if you want to listen to changes you should use ref.watch(menuProvider). Also as a tip you could use select to filter that value:

/// No reason to be ConsumerWidget because you're using a Consumer inside
class MenuCategoryComponent extends StatelessWidget {
  List<CategoryModel> allCategories = CategoryModel.allCategories;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: uiColor.second,
      child: ListView.builder(
          itemCount: allCategories.length,
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Consumer(builder: (context, ref, _) {
              final isSelected = ref.watch(menuProvider.select((v) => v.getSelected(allCategories[index])));
              return Container(
                color: isSelected
                    ? uiColor.comp_1
                    : uiColor.second,
                child: TextButton(
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.zero,
                    alignment: Alignment.center,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Text(allCategories[index].label!,
                        style: uiTextStyle.text1),
                  ),
                  onPressed: () {
                    ref
                        .read(menuProvider.notifier)
                        .setSelected(allCategories[index]);
                  },
                ),
              );
            });
          }
       ),
    );
  }
}


问:
How many ports count in the modern operating systems?
TCP and UDP protocols have 16-bit port field. Therefore operating systems network stacks, functions and structures have 16-bit values for the port.
But is it possible situation, when operating system has more than 65535 ports?</p>

答:
But is it possible situation, when operating system has more than 65535 ports?

Not with any protocol that uses a 16-bit field for the port number. It's not up to the operating system since it's part of the protocol and you cannot change that without changing all existing hosts.

As Ron Maupin has pointed out, that isn't normally a practical limitation since an application can use a single port to communicate with an arbitrary number of hosts. A socket is defined by the tuple source IP, destination IP, L4 protocol, source port, destination port. As long as that tuple is unique, the socket is unambiguously defined.

The number of L4 ports may become a bottleneck with network address (port) translation (NAPT) but business-grade NAT routers usually support using a pool of public IP addresses instead of just a single one.

What if "extended port number" exists only inside OS network stack for multiplex to isolated environments?

If you define your own transport-layer protocols you can make that field 128 bit if you wish. Practically, there's no need to do so.