问:
how to access snapshot.data inside Listview.builder inside futurebuilder
I am getting error The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

Mydata inside _categoriesList future

```<code>[
        {
            "business_category_id": 1,
            "business_category": "Manufacturer",
            "business_category_image": "164423936662011a06c450d.png"
        },
        {
            "business_category_id": 2,
            "business_category": "Distributor",
            "business_category_image": "164423937762011a11033aa.png"
        },
        {
            "business_category_id": 3,
            "business_category": "Wholesaler",
            "business_category_image": "164423938762011a1bb2e3c.png"
        },
        {
            "business_category_id": 4,
            "business_category": "Retailer",
            "business_category_image": "164423940062011a28189e5.png"
        },
        {
            "business_category_id": 5,
            "business_category": "Reseller",
            "business_category_image": "164423941362011a3554148.png"
        },
        {
            "business_category_id": 6,
            "business_category": "Service Provider",
            "business_category_image": "164423942462011a4096996.png"
        }
    ]
</code>```

my code inside futurebuilder. I am having problem accessing snapshot.data[index]

```<code>FutureBuilder(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {

          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)
</code>```

答:
Assuming you have a Category class, with variables for the CategoryId,CategoryName,CategoryImage with all the needed methods as shown in https://stackoverflow.com/a/71029334/12371668</p>
```<code>//create an instance of the category class before the build() method
final category = Category();

 @override
  Widget build(BuildContext context) {

     // other code

       FutureBuilder(
              future: category.fetchData(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                 List<Category> categories = snapshot.data();
                  return ListView.builder(
                      itemCount: categories.length,
                      itemBuilder: (context, index) {
                         var category = categories[index];
                        return Text(category.CategoryName);
                      });
                }
              },
        )
}
</code>```

Body:
I am getting error The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

Mydata inside _categoriesList future

[
        {
            "business_category_id": 1,
            "business_category": "Manufacturer",
            "business_category_image": "164423936662011a06c450d.png"
        },
        {
            "business_category_id": 2,
            "business_category": "Distributor",
            "business_category_image": "164423937762011a11033aa.png"
        },
        {
            "business_category_id": 3,
            "business_category": "Wholesaler",
            "business_category_image": "164423938762011a1bb2e3c.png"
        },
        {
            "business_category_id": 4,
            "business_category": "Retailer",
            "business_category_image": "164423940062011a28189e5.png"
        },
        {
            "business_category_id": 5,
            "business_category": "Reseller",
            "business_category_image": "164423941362011a3554148.png"
        },
        {
            "business_category_id": 6,
            "business_category": "Service Provider",
            "business_category_image": "164423942462011a4096996.png"
        }
    ]

my code inside futurebuilder. I am having problem accessing snapshot.data[index]

FutureBuilder(
      future: _categoriesList,
      builder: (_, snapshot) {
        if (snapshot.hasData) {

          return ListView.builder(
              itemCount: 6,
              itemBuilder: (_, index) {
                return Text(snapshot.data[index]); // error The method '[]' can't be unconditionally invoked because the receiver can be 'null'
              });
        }
      },
)

Body:
Assuming you have a Category class, with variables for the CategoryId,CategoryName,CategoryImage with all the needed methods as shown in https://stackoverflow.com/a/71029334/12371668

//create an instance of the category class before the build() method
final category = Category();

 @override
  Widget build(BuildContext context) {

     // other code

       FutureBuilder(
              future: category.fetchData(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                 List<Category> categories = snapshot.data();
                  return ListView.builder(
                      itemCount: categories.length,
                      itemBuilder: (context, index) {
                         var category = categories[index];
                        return Text(category.CategoryName);
                      });
                }
              },
        )
}


来源: stackexchange

问:
How to open goland from specific path?
This is actually a straightforward question, have been researching on how to use such command like code . for VSCode , but with GoLand in Windows. Any help please?

答:
GoLand works in a similar way to VSCode as covered in the docs:

```<code>goland64 .
</code>```

However for this to work the folder with goland64.exe will need to be in your path. You can test this without adding the folder to your path by specifying the full path to the executable; on my PC this is:

```<code>"C:\Program Files\JetBrains\GoLand 2021.3\bin\goland64.exe" .
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to open goland from specific path?

Body:
GoLand works in a similar way to VSCode as covered in the docs:

goland64 .

However for this to work the folder with goland64.exe will need to be in your path. You can test this without adding the folder to your path by specifying the full path to the executable; on my PC this is:

"C:\Program Files\JetBrains\GoLand 2021.3\bin\goland64.exe" .


问:
Pipeline hangs after starting Azurite

I used the following yml content. Used Azurite 3.15 and 3.9. But no luck. Then I tried as separate jobs. Still unable to pass the integration test.

```<code> stages:
    - stage: Publish
      displayName: 'Build and Publish Artifacts'
      jobs:
      - job: 'NGKMediaManagementAPI'
        steps:
        - task: NodeTool@0
          inputs:
             versionSpec: 13.x
        - script : npm install -g azurite@3.9.0
        - script : mkdir azurite
        - script : azurite
</code>```

答:
When starting Azurite, the default is for it to block the command prompt you're running it on which makes the pipeline appear to hang.

Run the command from PowerShell and Use the background operator to start a background job.

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      npm install -g azurite
      azurite &
```

More information: Run automated tests by using Azurite - Run tests on Azure Pipelines. In this example they use the & operator in Bash which also directs the shell to run the command in the background.

Other interesting commands around this are Get-Job, Stop-Job and Remove-Job.

Title: Pipeline hangs after starting Azurite

Body:
I used the following yml content. Used Azurite 3.15 and 3.9. But no luck. Then I tried as separate jobs. Still unable to pass the integration test.

 stages:
    - stage: Publish
      displayName: 'Build and Publish Artifacts'
      jobs:
      - job: 'NGKMediaManagementAPI'
        steps:
        - task: NodeTool@0
          inputs:
             versionSpec: 13.x
        - script : npm install -g azurite@3.9.0
        - script : mkdir azurite
        - script : azurite

Body:
When starting Azurite, the default is for it to block the command prompt you're running it on which makes the pipeline appear to hang.

Run the command from PowerShell and Use the background operator to start a background job.

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      npm install -g azurite
      azurite &

More information: Run automated tests by using Azurite - Run tests on Azure Pipelines. In this example they use the & operator in Bash which also directs the shell to run the command in the background.

Other interesting commands around this are Get-Job, Stop-Job and Remove-Job.


问:
SQL Server: Invalid Column Name
I am working on modifying the existing SQL Server stored procedure. I added two new columns to the table and modified the stored procedure as well to select these two columns as well. Although the columns are available in the table, I keep getting this error:

Invalid column name 'INCL_GSTAMOUNT'

Can anyone please tell me what's wrong here?

答: I experienced similar problem when running a query from the code (C#) side. The column in the table that was bringing the above error had 'default value or binding' (when I checked the table's design) already added. So I just removed the column and its corresponding value as data being inserted by the query</p>

Title: SQL Server: Invalid Column Name


问:
Automate forking a github repository
Here is a script in Python that is used to clone repositories given the github account name (source_account), the name of the source repo (source_repo), and the source branch (source_branch). Is there a way I could change this in order to Fork all public repo's from a User's account given a username?</p>
```<code>import git
import os
import pandas as pd
import pandasql as ps

# reading csv file of Github_account_details
df = pd.read_csv('github_account_details.csv')

source_accounts = df['source_account'].unique()  # taking all distinct account names

print("****Please select a GitHub account from which you want to clone the Repositories****")

for names in source_accounts:
    print('-->', names)
selected_account = input()  # taking input from user for selecting the particular account

# extracting all the repositories for user's selected account
selected_repo = ps.sqldf(f"select source_repo from df where source_account = '{selected_account}'")
to_clone_repos = []

# making new list with 'source_repo' header
for i in selected_repo.index:
    to_clone_repos.append(selected_repo['source_repo'][i])

total_repos_count = len(to_clone_repos)
print(f"Total repositories in {selected_account} are: {total_repos_count}\n{to_clone_repos}")
permission_to_clone = input("Give permission to Clone Y/N")

# cloning all the repos from to_clone_repos
if permission_to_clone == 'Y' or permission_to_clone == 'Yes' or permission_to_clone == 'YES' or permission_to_clone == 'yes':
    for repos in to_clone_repos:
        if not os.path.exists(selected_account):
            os.makedirs(selected_account)
        print(f"{repos} -- Cloning in Progress")
        git.Git(f'{selected_account}/').clone(f'https://github.com/{selected_account}/{repos}.git')
        print(f"{repos} -- Cloned successfully")
</code>```

答:
In your case (python program), you can use sigmavirus24/github3.py which give you access to a wrapper to GitHub CLI.

The gh repo fork command mentioned in the comments is available through their own API functions.

repository = self.gh.repository("kennethreitz", "requests")
forked_repo = repository.create_fork()
assert isinstance(forked_repo, github3.repos.Repository)

org_forked_repo = repository.create_fork("github3py")
assert isinstance(org_forked_repo, github3.repos.Repository)
```

Title: Automate forking a github repository

Body:
Here is a script in Python that is used to clone repositories given the github account name (source_account), the name of the source repo (source_repo), and the source branch (source_branch). Is there a way I could change this in order to Fork all public repo's from a User's account given a username?

import git
import os
import pandas as pd
import pandasql as ps

# reading csv file of Github_account_details
df = pd.read_csv('github_account_details.csv')

source_accounts = df['source_account'].unique()  # taking all distinct account names

print("****Please select a GitHub account from which you want to clone the Repositories****")

for names in source_accounts:
    print('-->', names)
selected_account = input()  # taking input from user for selecting the particular account

# extracting all the repositories for user's selected account
selected_repo = ps.sqldf(f"select source_repo from df where source_account = '{selected_account}'")
to_clone_repos = []

# making new list with 'source_repo' header
for i in selected_repo.index:
    to_clone_repos.append(selected_repo['source_repo'][i])

total_repos_count = len(to_clone_repos)
print(f"Total repositories in {selected_account} are: {total_repos_count}\n{to_clone_repos}")
permission_to_clone = input("Give permission to Clone Y/N")

# cloning all the repos from to_clone_repos
if permission_to_clone == 'Y' or permission_to_clone == 'Yes' or permission_to_clone == 'YES' or permission_to_clone == 'yes':
    for repos in to_clone_repos:
        if not os.path.exists(selected_account):
            os.makedirs(selected_account)
        print(f"{repos} -- Cloning in Progress")
        git.Git(f'{selected_account}/').clone(f'https://github.com/{selected_account}/{repos}.git')
        print(f"{repos} -- Cloned successfully")


问:
StorageBackend version is incompatible with current JanusGraph version
Unable to start gremlin-server due to version mismatch. How can I fix this issue?

Here is the full stack trace

```<code>Exception in thread "main" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at org.apache.tinkerpop.gremlin.server.util.ServerGremlinExecutor.<init>(ServerGremlinExecutor.java:121)
    at org.apache.tinkerpop.gremlin.server.util.ServerGremlinExecutor.<init>(ServerGremlinExecutor.java:89)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.<init>(GremlinServer.java:110)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.main(GremlinServer.java:354)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.tinkerpop.gremlin.server.util.ServerGremlinExecutor.<init>(ServerGremlinExecutor.java:110)
    ... 3 more
Caused by: org.janusgraph.core.JanusGraphException: StorageBackend version is incompatible with current JanusGraph version: storage [0.2.1] vs. runtime [0.2.0]
    at org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.<init>(GraphDatabaseConfiguration.java:1427)
    at org.janusgraph.core.JanusGraphFactory.lambda$open$0(JanusGraphFactory.java:152)
    at org.janusgraph.graphdb.management.JanusGraphManager.openGraph(JanusGraphManager.java:210)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:151)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:101)
    at org.janusgraph.graphdb.management.JanusGraphManager.lambda$new$0(JanusGraphManager.java:65)
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
    at org.janusgraph.graphdb.management.JanusGraphManager.<init>(JanusGraphManager.java:64)
    ... 8 more
Exception in thread "gremlin-server-shutdown" java.lang.NullPointerException
    at org.apache.tinkerpop.gremlin.server.GremlinServer.stop(GremlinServer.java:264)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.lambda$new$0(GremlinServer.java:91)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I am working with janusgraph-0.2.0-hadoop2.zip downloaded from janusgraph website. I don't know why the error says it has janusgraph 0.2.1

答:
You need to add the following property in your configuration file. This property will allow upgrade and DB get compatible with the newer version.

graph.allow-upgrade=true

Name
Description
Datatype
Default Value

graph.allow-upgrade
Setting this to true will allow certain fixed values to be updated such as storage-version. This should only be used for upgrading.
Boolean
false

Body:
Unable to start gremlin-server due to version mismatch. How can I fix this issue?

Here is the full stack trace

Exception in thread "main" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at org.apache.tinkerpop.gremlin.server.util.ServerGremlinExecutor.<init>(ServerGremlinExecutor.java:121)
    at org.apache.tinkerpop.gremlin.server.util.ServerGremlinExecutor.<init>(ServerGremlinExecutor.java:89)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.<init>(GremlinServer.java:110)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.main(GremlinServer.java:354)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.tinkerpop.gremlin.server.util.ServerGremlinExecutor.<init>(ServerGremlinExecutor.java:110)
    ... 3 more
Caused by: org.janusgraph.core.JanusGraphException: StorageBackend version is incompatible with current JanusGraph version: storage [0.2.1] vs. runtime [0.2.0]
    at org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.<init>(GraphDatabaseConfiguration.java:1427)
    at org.janusgraph.core.JanusGraphFactory.lambda$open$0(JanusGraphFactory.java:152)
    at org.janusgraph.graphdb.management.JanusGraphManager.openGraph(JanusGraphManager.java:210)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:151)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:101)
    at org.janusgraph.graphdb.management.JanusGraphManager.lambda$new$0(JanusGraphManager.java:65)
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
    at org.janusgraph.graphdb.management.JanusGraphManager.<init>(JanusGraphManager.java:64)
    ... 8 more
Exception in thread "gremlin-server-shutdown" java.lang.NullPointerException
    at org.apache.tinkerpop.gremlin.server.GremlinServer.stop(GremlinServer.java:264)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.lambda$new$0(GremlinServer.java:91)
    at java.lang.Thread.run(Thread.java:748)

I am working with janusgraph-0.2.0-hadoop2.zip downloaded from janusgraph website. I don't know why the error says it has janusgraph 0.2.1


问:
Create an Azure Internal Loadbalancer with Zone Redundant Properties
This is the command that I tried to use and the error message received is shown below the command

```<code>az network lb create --name <name> -g <RG name> --frotnend-ip-name <frontend_name> --frontend-ip-zone "1","2","3" -l southeastasia --private-ip-address <“static_ip”> --private-ip-address-version IPv4 --sku Standard --subnet “<subnet_id>” --subnet-address-prefix “<prefix>” --vnet-name “<vnet_name>” --public-ip-address “”
</code>```

Below is the error received for the command

```<code>az network lb create: '1, 2, 3' is not a valid value for '--frontend-ip-zone'. Allowed values: 1, 2, 3.
</code>```

答:
You should first create the LB then add frontend-IP to the LB,

Create LB:

```<code>az network lb create -g MyResourceGroup -n MyLb --sku Standard
</code>```

Add Zone redundant frontend across Zones,

```<code>az network lb frontend-ip create -g {rg} --lb-name lb -n LoadBalancerFrontEnd -z 1 2 3 --vnet-name vnet --subnet subnet
</code>```

We are working on Public PR to enable this feature during the creation of LB itself.

Body:
This is the command that I tried to use and the error message received is shown below the command

az network lb create --name <name> -g <RG name> --frotnend-ip-name <frontend_name> --frontend-ip-zone "1","2","3" -l southeastasia --private-ip-address <“static_ip”> --private-ip-address-version IPv4 --sku Standard --subnet “<subnet_id>” --subnet-address-prefix “<prefix>” --vnet-name “<vnet_name>” --public-ip-address “”

Below is the error received for the command

az network lb create: '1, 2, 3' is not a valid value for '--frontend-ip-zone'. Allowed values: 1, 2, 3.

Body:
You should first create the LB then add frontend-IP to the LB,

Create LB:

az network lb create -g MyResourceGroup -n MyLb --sku Standard

Add Zone redundant frontend across Zones,

az network lb frontend-ip create -g {rg} --lb-name lb -n LoadBalancerFrontEnd -z 1 2 3 --vnet-name vnet --subnet subnet

We are working on Public PR to enable this feature during the creation of LB itself.


问:
Converting varying JSON objects to CSV-file
I am calling an API and it returns JSON string. I want to convert it to CSV-format so I can save it later to database. However, JSON objects keys cause problems because there is keys missing or keys are changing.
I wrote this python script but because of keys I cannot get it to work:

```<code>import json
import csv

with open('custom.json') as json_file:
    data = json.load(json_file)

custom_data = data['CustomJSON']
data_file = open('data_file.csv', 'w')
csv_writer = csv.writer(data_file)
count = 0

for i in custom_data:
    if count == 0:
        # Writing headers of CSV file
        header = i.keys()
        csv_writer.writerow(header)
        count += 1
    # Writing data of CSV file
    csv_writer.writerow(i.values())
data_file.close()
</code>```

How I can convert this type of JSON to CSV?
Example JSON message:

```<code>{
    "CustomJSON" : [
    {
     "id" : "1,
      "name" : "Jack",
      "surname" : "Bauer"
    },
    {
      "id" : "2",
      "name" : "John",
      "surname" : "Smith"
      "age" : "31",
      "city" : "New York"
    },
    {
      "id" : "3",
      "name" : "Matt",
      "surname" : "Secret"
      "exception_1" : "Exception_1",
      "exception_2" : "Exception_2"
      "date" : "2022-02-08"
    }
  ]
}
</code>```

Should I try to loop all key-values first somehow and then later try to add data? Can anyone provide an example?

答:
I am a pandas fan(atic) so I'd do something like

import pandas as pd

# df is a pandas dataframe)
df = pd.read_json('http://data.com/foo')
df.to_csv('foo.csv')
```

Pandas has options for the CSV dialect, if need be. You should be able to do what you describe with those two function calls, though.

Body:
I am calling an API and it returns JSON string. I want to convert it to CSV-format so I can save it later to database. However, JSON objects keys cause problems because there is keys missing or keys are changing.
I wrote this python script but because of keys I cannot get it to work:

import json
import csv

with open('custom.json') as json_file:
    data = json.load(json_file)

custom_data = data['CustomJSON']
data_file = open('data_file.csv', 'w')
csv_writer = csv.writer(data_file)
count = 0

for i in custom_data:
    if count == 0:
        # Writing headers of CSV file
        header = i.keys()
        csv_writer.writerow(header)
        count += 1
    # Writing data of CSV file
    csv_writer.writerow(i.values())
data_file.close()

How I can convert this type of JSON to CSV?
Example JSON message:

{
    "CustomJSON" : [
    {
     "id" : "1,
      "name" : "Jack",
      "surname" : "Bauer"
    },
    {
      "id" : "2",
      "name" : "John",
      "surname" : "Smith"
      "age" : "31",
      "city" : "New York"
    },
    {
      "id" : "3",
      "name" : "Matt",
      "surname" : "Secret"
      "exception_1" : "Exception_1",
      "exception_2" : "Exception_2"
      "date" : "2022-02-08"
    }
  ]
}

Should I try to loop all key-values first somehow and then later try to add data? Can anyone provide an example?

Body:
I am a pandas fan(atic) so I'd do something like

import pandas as pd

# df is a pandas dataframe)
df = pd.read_json('http://data.com/foo')
df.to_csv('foo.csv')

Pandas has options for the CSV dialect, if need be. You should be able to do what you describe with those two function calls, though.


问:
How to solve Error when save Entity with List
I have next Entity(List was added with last update):

```<code>@Entity
@Table(name = "settings", schema = "notpublic")
public class Settings {

    @Id
    @GeneratedValue(generator = "settings_seq", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "settings_seq", sequenceName = "notpublic.settings_seq", schema = "notpublic", allocationSize = 1)
    private Long id;

    @Column
    private String code;

    @ElementCollection
    @CollectionTable(name = "settings_bank", joinColumns = { @JoinColumn(name = "id") })
    @Column(name = "bank_id")
    private List<Long> bankIds;
</code>```

And liquibase update:

```<code><createTable tableName="settings_bank" schemaName="notpublic">
            <column name="id" type="BIGINT">
                <constraints nullable="false"/>
            </column>
            <column name="bank_id" type="BIGINT">
                <constraints nullable="false"/>
            </column>
        </createTable>
</code>```

Well, when I try to save entity I get rg.postgresql.util.PSQLException: ERROR: relation "settings_bank" does not exist. I connect to DB by pgAdmin and- table was created..
List bankIds- just Long, its not connect to another Entity.
What I missed and how to fix it?

答: I solve it, forget schema in @CollectionTable</p>

Body:
I have next Entity(List was added with last update):

@Entity
@Table(name = "settings", schema = "notpublic")
public class Settings {

    @Id
    @GeneratedValue(generator = "settings_seq", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "settings_seq", sequenceName = "notpublic.settings_seq", schema = "notpublic", allocationSize = 1)
    private Long id;

    @Column
    private String code;

    @ElementCollection
    @CollectionTable(name = "settings_bank", joinColumns = { @JoinColumn(name = "id") })
    @Column(name = "bank_id")
    private List<Long> bankIds;

And liquibase update:

<createTable tableName="settings_bank" schemaName="notpublic">
            <column name="id" type="BIGINT">
                <constraints nullable="false"/>
            </column>
            <column name="bank_id" type="BIGINT">
                <constraints nullable="false"/>
            </column>
        </createTable>

Well, when I try to save entity I get rg.postgresql.util.PSQLException: ERROR: relation "settings_bank" does not exist. I connect to DB by pgAdmin and- table was created..
List bankIds- just Long, its not connect to another Entity.
What I missed and how to fix it?


问:
How to access query params inside getServerSideProps in Next.js?
I am trying to use get getServerSideProps in my code and I am not able to do it because I am not able to pass router.query.itmid.

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const router = useRouter();
  var id = router.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
```

Here is what I tried
https://codesandbox.io/s/youthful-lucy-427g1?file=/src/App.js

I am new to Next.js and and I have no much knowledge of Next.js so please don't tell me to read the docs if I understand the docs I wouldn't be asking this question.

答:
You should use context in getServerSideProps to get query params</p>
```<code>export async function getServerSideProps(ctx) {
  // Call an external API endpoint to get posts
  var id = ctx.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
</code>```

Body:
I am trying to use get getServerSideProps in my code and I am not able to do it because I am not able to pass router.query.itmid.

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const router = useRouter();
  var id = router.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}

Here is what I tried
https://codesandbox.io/s/youthful-lucy-427g1?file=/src/App.js

I am new to Next.js and and I have no much knowledge of Next.js so please don't tell me to read the docs if I understand the docs I wouldn't be asking this question.

Body:
You should use context in getServerSideProps to get query params

export async function getServerSideProps(ctx) {
  // Call an external API endpoint to get posts
  var id = ctx.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}


问:
Split comma delimited names in Microsoft Report Builder
In my database, I have a column, which lists names.  Names are in this format:

surname, first name, surname, first name

e.g:  bloggs, joe, jackson, samuel

I'm assuming I will use a 'split' expression, but how do I write it so that it appears in my report as:

surname, first name

surname, first name

Thanks

答:
test table

```<code>declare @t table(ch varchar(max))
insert into @t values('bloggs, joe, jackson, samuel')
</code>```

your query PARSENAME(REPLACE) divide your table into columns based on character after , like

```<code>SELECT
PARSENAME(REPLACE(ch,',','.'),4) 'Surname1' ,
PARSENAME(REPLACE(ch,',','.'),3) 'FirstName1',
PARSENAME(REPLACE(ch,',','.'),2) 'Surname2',
PARSENAME(REPLACE(ch,',','.'),1) 'FirstName2'
FROM @t
</code>```

then use union in order to put it in columns, or concat to put your value in a single column.

```<code>SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),4),',',
PARSENAME(REPLACE(ch,',','.'),3) )'Names'
FROM @t
UNION all
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2),',',
PARSENAME(REPLACE(ch,',','.'),1) )'Names'
from @t
</code>```

if your column has more than two name then use updated syntax with descending order

```<code>------------(K) Ordered Pair--------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2K),',',
PARSENAME(REPLACE(ch,',','.'),2K-1) )'Names'
FROM @t
UNION all
------------(K-1) Ordered Pair-------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2K-2),',',
PARSENAME(REPLACE(ch,',','.'),2K-3) )'Names'
from @t
/*--------------------------------------*/
/*--------------------------------------*/
/*--------------------------------------*/
------------(2) Ordered Pair--------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),4),',',
PARSENAME(REPLACE(ch,',','.'),3) )'Names'
FROM @t
UNION all
------------(1) Ordered Pair--------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2),',',
PARSENAME(REPLACE(ch,',','.'),1) )'Names'
from @t
</code>```

The other-way is using string_split to split charchter,NTILE to give it rank and string_agg to results into one column that enables you to have more than 2 names

```<code>select string_agg(value,',') from
(
SELECT
value , NTILE (2) OVER (
ORDER BY value
) ID
FROM @t
cross apply
STRING_SPLIT(ch, ',')) t
group by ID
</code>```

Body:
test table

declare @t table(ch varchar(max))
insert into @t values('bloggs, joe, jackson, samuel')

your query PARSENAME(REPLACE) divide your table into columns based on character after , like

SELECT
PARSENAME(REPLACE(ch,',','.'),4) 'Surname1' ,
PARSENAME(REPLACE(ch,',','.'),3) 'FirstName1',
PARSENAME(REPLACE(ch,',','.'),2) 'Surname2',
PARSENAME(REPLACE(ch,',','.'),1) 'FirstName2'
FROM @t

then use union in order to put it in columns, or concat to put your value in a single column.

SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),4),',',
PARSENAME(REPLACE(ch,',','.'),3) )'Names'
FROM @t
UNION all
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2),',',
PARSENAME(REPLACE(ch,',','.'),1) )'Names'
from @t

if your column has more than two name then use updated syntax with descending order

------------(K) Ordered Pair--------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2K),',',
PARSENAME(REPLACE(ch,',','.'),2K-1) )'Names'
FROM @t
UNION all
------------(K-1) Ordered Pair-------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2K-2),',',
PARSENAME(REPLACE(ch,',','.'),2K-3) )'Names'
from @t
/*--------------------------------------*/
/*--------------------------------------*/
/*--------------------------------------*/
------------(2) Ordered Pair--------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),4),',',
PARSENAME(REPLACE(ch,',','.'),3) )'Names'
FROM @t
UNION all
------------(1) Ordered Pair--------------
SELECT
concat(
PARSENAME(REPLACE(ch,',','.'),2),',',
PARSENAME(REPLACE(ch,',','.'),1) )'Names'
from @t

The other-way is using string_split to split charchter,NTILE to give it rank and string_agg to results into one column that enables you to have more than 2 names

select string_agg(value,',') from
(
SELECT
value , NTILE (2) OVER (
ORDER BY value
) ID
FROM @t
cross apply
STRING_SPLIT(ch, ',')) t
group by ID


问:
Programming practice: the price of laptops list problem
This is the question that given to me

One day Sindakht and Irsa were discussing the price of laptops and their quality. Sindakht guesses that the more expensive a laptop is, the better the quality. But Irsa claims that she can find 2 laptops whose price is lower than the first, but its quality is higher than the second, and she can refute Sindakht's guess. Now you have to write a program to help Irsa investigate her claim.

N laptop specifications will be given to you. The first input line contains the number n, which indicates the number of laptops. Each of the next n lines contains two numbers, the first of which indicates the price of the laptop and the second of which indicates the quality of the laptop. If you can find two laptops that meet the conditions stated by Irsa, print happy irsa, otherwise print poor irsa (please note the lower case letters, all letters are written in lower case).

Sample input:

```<code>2
1 10
7 3
</code>```

Sample output:

```<code>happy irsa
</code>```

At the input of the sample, the first laptop is priced at 1 and the quality is 10 (the higher the number, the higher the quality). The second laptop is priced at 7 and the quality is 3. Well, Irsa has managed to find two laptops, which although the price of the latter is higher than the price of the first, but the quality of the latter is lower than the quality of the first.

Sample input:

```<code>4
1 5
7 9
5 6
20 30
</code>```

Sample output:

```<code>poor irsa
</code>```

and I try this Anyone can help me to make it Right

```<code>n=int(input())
computer=[]

for m in range(n) :
    laptop=input()
    laptop=laptop.split()
    computer.append(laptop)

for i in range(n) :
    for j in range(2):
        computer[i][j]=int(computer[i][j])

for i in range(n+1) :
    if computer[i][0] < computer[i+1][0] and computer[i][1] > computer[i+1][1] :
        print("happy irsa")
        break
    else:
        print("poor irsa")
        break
</code>```

答:
You need to compare every pair of laptops, so you need nested loops.

You should only break out of the loop when you find a pair that makes Irsa happy. If you end without breaking, Irsa is sad, you can use the else: blocb for this.

```<code>irsa_happy = False

for c1 in computer:
    for c2 in computer:
        if c1[0] < c2[0] and c1[1] > c2[1]:
            print("happy irsa")
            irsa_happy = True
            break
    if irsa_happy:
        break
else:
    print("poor irsa")
</code>```

Body:
This is the question that given to me

One day Sindakht and Irsa were discussing the price of laptops and their quality. Sindakht guesses that the more expensive a laptop is, the better the quality. But Irsa claims that she can find 2 laptops whose price is lower than the first, but its quality is higher than the second, and she can refute Sindakht's guess. Now you have to write a program to help Irsa investigate her claim.

N laptop specifications will be given to you. The first input line contains the number n, which indicates the number of laptops. Each of the next n lines contains two numbers, the first of which indicates the price of the laptop and the second of which indicates the quality of the laptop. If you can find two laptops that meet the conditions stated by Irsa, print happy irsa, otherwise print poor irsa (please note the lower case letters, all letters are written in lower case).

Sample input:

2
1 10
7 3

Sample output:

happy irsa

At the input of the sample, the first laptop is priced at 1 and the quality is 10 (the higher the number, the higher the quality). The second laptop is priced at 7 and the quality is 3. Well, Irsa has managed to find two laptops, which although the price of the latter is higher than the price of the first, but the quality of the latter is lower than the quality of the first.

Sample input:

4
1 5
7 9
5 6
20 30

Sample output:

poor irsa

and I try this Anyone can help me to make it Right

n=int(input())
computer=[]

for m in range(n) :
    laptop=input()
    laptop=laptop.split()
    computer.append(laptop)

for i in range(n) :
    for j in range(2):
        computer[i][j]=int(computer[i][j])

for i in range(n+1) :
    if computer[i][0] < computer[i+1][0] and computer[i][1] > computer[i+1][1] :
        print("happy irsa")
        break
    else:
        print("poor irsa")
        break

Body:
You need to compare every pair of laptops, so you need nested loops.

You should only break out of the loop when you find a pair that makes Irsa happy. If you end without breaking, Irsa is sad, you can use the else: blocb for this.

irsa_happy = False

for c1 in computer:
    for c2 in computer:
        if c1[0] < c2[0] and c1[1] > c2[1]:
            print("happy irsa")
            irsa_happy = True
            break
    if irsa_happy:
        break
else:
    print("poor irsa")


问:
Atlassian Bitbucket + Python
Editing to create a  minimal reproducible example:
I am importing bitbucket and Bitbucket because even though the docs indicate 'bitbucket', I get errors that there is no attribute for repo_list; see below
My code is:

```<code>
from atlassian import Bitbucket
from atlassian import bitbucket
from atlassian.bitbucket import Cloud

bitbucket_username = 'username'
scraper_token = 'token'

Bitbucket_app_pw = Cloud(
    username=bitbucket_username,
    password=scraper_token,
    cloud=True)

try:
    repo_list = bitbucket.repo_list("SOL")
    print(repo_list)
    projects = bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = bitbucket.project("SOL")
    print(data)
    project_info = bitbucket.project("SOL")
    print(project_info)
except AttributeError:
    project_key = "SOL"
    repo_list = Bitbucket.repo_list("SOL")
    print(repo_list)
    projects = Bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = Bitbucket.project("SOL")
    print(data)
    project_info = Bitbucket.project("SOL")
    print(project_info)

</code>```

My error is:

```<code>Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 16, in <module>
    repo_list = bitbucket.repo_list("SOL")
AttributeError: module 'atlassian.bitbucket' has no attribute 'repo_list'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 28, in <module>
    repo_list = Bitbucket.repo_list("SOL")
TypeError: Bitbucket.repo_list() missing 1 required positional argument: 'project_key'

</code>```

Original Question_

I am trying to log into a Atlassian BitBucket repository using the App Password, and it looks like I am in. But when I try to get a list of repositories in a project (using https://atlassian-python-api.readthedocs.io/bitbucket.html), I keep on getting an error. For example, the project key that I am trying to access is 'SOL'. So when I run:

```<code>Bitbucket.project_list('SOL')
</code>```

I get an error:

```<code>AttributeError: 'str' object has no attribute '_url_projects'
</code>```

Not sure what I am doing wrong here. Any advice?
TIA!

Editing after people left helpful comments:
So when I tried the suggestion given by AKX:

```<code>data = bitbucket.project("SOL")
print(data)
</code>```

The response was:

```<code>AttributeError: module 'atlassian.bitbucket' has no attribute 'project'
</code>```

答:
If you want to use atlassian.bitbucket.Cloud, you'd need something like

```<code>from atlassian.bitbucket import Cloud

bitbucket_username = 'username'
scraper_token = 'token'

bb = Cloud(
    username=bitbucket_username,
    password=scraper_token,
    cloud=True,
)

repo_list = bb.repo_list("SOL")
print(repo_list)
projects = bb.project_list()
print(projects)
data = bb.project("SOL")
print(data)
project_info = bb.project("SOL")
print(project_info)
</code>```

Original

You will need to instantiate the Bitbucket class first; based on your spelling, you're trying to access an instance method.

Based on the examples in the docs:

```<code>from atlassian import Bitbucket

bitbucket = Bitbucket(
        url='http://localhost:8080',
        username='admin',
        password='admin')

data = bitbucket.project("SOL")
print(data)
</code>```

(note that project_list() does not accept a parameter anyway; if you want a project's info, use project().)

Title: Atlassian Bitbucket + Python

Body:
Editing to create a  minimal reproducible example:
I am importing bitbucket and Bitbucket because even though the docs indicate 'bitbucket', I get errors that there is no attribute for repo_list; see below
My code is:

from atlassian import Bitbucket
from atlassian import bitbucket
from atlassian.bitbucket import Cloud

bitbucket_username = 'username'
scraper_token = 'token'

Bitbucket_app_pw = Cloud(
    username=bitbucket_username,
    password=scraper_token,
    cloud=True)

try:
    repo_list = bitbucket.repo_list("SOL")
    print(repo_list)
    projects = bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = bitbucket.project("SOL")
    print(data)
    project_info = bitbucket.project("SOL")
    print(project_info)
except AttributeError:
    project_key = "SOL"
    repo_list = Bitbucket.repo_list("SOL")
    print(repo_list)
    projects = Bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = Bitbucket.project("SOL")
    print(data)
    project_info = Bitbucket.project("SOL")
    print(project_info)

My error is:

Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 16, in <module>
    repo_list = bitbucket.repo_list("SOL")
AttributeError: module 'atlassian.bitbucket' has no attribute 'repo_list'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 28, in <module>
    repo_list = Bitbucket.repo_list("SOL")
TypeError: Bitbucket.repo_list() missing 1 required positional argument: 'project_key'

Original Question_

I am trying to log into a Atlassian BitBucket repository using the App Password, and it looks like I am in. But when I try to get a list of repositories in a project (using https://atlassian-python-api.readthedocs.io/bitbucket.html), I keep on getting an error. For example, the project key that I am trying to access is 'SOL'. So when I run:

Bitbucket.project_list('SOL')

I get an error:

AttributeError: 'str' object has no attribute '_url_projects'

Not sure what I am doing wrong here. Any advice?
TIA!

Editing after people left helpful comments:
So when I tried the suggestion given by AKX:

data = bitbucket.project("SOL")
print(data)

The response was:

AttributeError: module 'atlassian.bitbucket' has no attribute 'project'

Body:
If you want to use atlassian.bitbucket.Cloud, you'd need something like

from atlassian.bitbucket import Cloud

bitbucket_username = 'username'
scraper_token = 'token'

bb = Cloud(
    username=bitbucket_username,
    password=scraper_token,
    cloud=True,
)

repo_list = bb.repo_list("SOL")
print(repo_list)
projects = bb.project_list()
print(projects)
data = bb.project("SOL")
print(data)
project_info = bb.project("SOL")
print(project_info)

Original

You will need to instantiate the Bitbucket class first; based on your spelling, you're trying to access an instance method.

Based on the examples in the docs:

from atlassian import Bitbucket

bitbucket = Bitbucket(
        url='http://localhost:8080',
        username='admin',
        password='admin')

data = bitbucket.project("SOL")
print(data)

(note that project_list() does not accept a parameter anyway; if you want a project's info, use project().)


问:
How to prevent multiple 'as const' on TypeScript
How can I prevent multiple 'as const' needing by declaring an interface or a type to solve this issue below?</p>
```<code>export const MESSAGES = {
    WELlCOME_MESSAGE: 'Wellcome again' as const,
    UNALLOWED_MESSAGE: 'You are not allowed' as const,
    ALLOWED_MESSAGE: 'You are allowed' as const,
}
</code>```

答:
Just declare as const on the object level instead:

```<code>export const MESSAGES = {
    WELlCOME_MESSAGE: 'Wellcome again',
    UNALLOWED_MESSAGE: 'You are not allowed',
    ALLOWED_MESSAGE: 'You are allowed',
} as const;
</code>```

See example on TypeScript Playground.

Body:
How can I prevent multiple 'as const' needing by declaring an interface or a type to solve this issue below?

export const MESSAGES = {
    WELlCOME_MESSAGE: 'Wellcome again' as const,
    UNALLOWED_MESSAGE: 'You are not allowed' as const,
    ALLOWED_MESSAGE: 'You are allowed' as const,
}

Body:
Just declare as const on the object level instead:

export const MESSAGES = {
    WELlCOME_MESSAGE: 'Wellcome again',
    UNALLOWED_MESSAGE: 'You are not allowed',
    ALLOWED_MESSAGE: 'You are allowed',
} as const;

See example on TypeScript Playground.


问:
Every shared user (edit rights) can take over the web app within a Google domain
It seems that a user with whom the apps script is shared can deploy a web app. The web app url stays the same as it was when executed by the original account, but now is executed from this user's account. You don't have to be owner of the script within a Google Domain. Is there a way to protect this?
That means:

edit rights in the spreadsheet & attached apps script code

not being able to deploy a web app (only the owner will be able)

答:
It's not currently possible to do this, as anyone with edit access to a Spreadsheet also has edit access to any script that is bound to it. Changing the web app view permissions to 'only me' does stop this from happening, but only because re-publishing as a second user completely breaks the web app in the first place.

Feature Request:

You can however let Google know that this is a feature that is important for access to their APIs, and that you would like to request they implement it.

Google's Issue Tracker is a place for developers to report issues and make feature requests for their development services, I'd urge you to make a feature request there. The best component to file this under would be the Google  Apps Script component, with the Feature Request template.


问:
Is it possible to pivot in this way with pandas?
I have this dataframe.

report_id
landcover_type
data_type
mean
area

615
Acid grassland
canopyheight
2
493.9125

615
Arable and horticulture
canopyheight
4
0.86

615
Acid grassland
carbonstoragewoodlands
8
493.9125

615
Arable and horticulture
carbonstoragewoodlands
161
0.86

is it possible to pivot it so I have a new column for each distinct data_type with their own aggregation of my choosing like this?

report_id
landcover_type
canopyheight_mean
carbonstorage_total
area

615
Acid Grassland
2
8
493.9125

615
Arable and horticulture
4
161
493.9125

答:
If need change aggregate function by data - if numeric aggregate mean else aggregate join use:

```<code>print (df)
   report_id           landcover_type               data_type  mean area
0        615           Acid grassland            canopyheight     2   aa
1        615           Acid grassland            canopyheight     7   rr
2        615  Arable and horticulture            canopyheight     4   ss
3        615           Acid grassland  carbonstoragewoodlands     8   dd
4        615  Arable and horticulture  carbonstoragewoodlands   161   ff
f = lambda x: x.mean() if np.issubdtype(x.dtype, np.number) else ','.join(x)
df1 = df.pivot_table(index=['report_id', 'landcover_type'],
                     columns= 'data_type',
                     aggfunc=f)

df1.columns = df1.columns.map('_'.join)
df1 = df1.reset_index()
print (df1)
   report_id           landcover_type area_canopyheight  \
0        615           Acid grassland             aa,rr
1        615  Arable and horticulture                ss

  area_carbonstoragewoodlands  mean_canopyheight  mean_carbonstoragewoodlands
0                          dd                4.5                          8.0
1                          ff                4.0                        161.0
</code>```

Body:
If need change aggregate function by data - if numeric aggregate mean else aggregate join use:

print (df)
   report_id           landcover_type               data_type  mean area
0        615           Acid grassland            canopyheight     2   aa
1        615           Acid grassland            canopyheight     7   rr
2        615  Arable and horticulture            canopyheight     4   ss
3        615           Acid grassland  carbonstoragewoodlands     8   dd
4        615  Arable and horticulture  carbonstoragewoodlands   161   ff
f = lambda x: x.mean() if np.issubdtype(x.dtype, np.number) else ','.join(x)
df1 = df.pivot_table(index=['report_id', 'landcover_type'],
                     columns= 'data_type',
                     aggfunc=f)

df1.columns = df1.columns.map('_'.join)
df1 = df1.reset_index()
print (df1)
   report_id           landcover_type area_canopyheight  \
0        615           Acid grassland             aa,rr
1        615  Arable and horticulture                ss

  area_carbonstoragewoodlands  mean_canopyheight  mean_carbonstoragewoodlands
0                          dd                4.5                          8.0
1                          ff                4.0                        161.0


问:
Broadcast to multiple reactive WebSocketSessions created using springboot webflux is not working
Following is the scenario:

I create a reactor kafka receiver

Data consumed from kafka receiver is published to a WebSocketHanlder

WebSocketHanlder is mapped to a URL using SimpleUrlHandlerMapping

URL pattern is api/v1/ws/{ID} and I expect multiple WebSocketSession to get created based on different ID used in URI which are managed by single WebSocketHanlder, which is actually happening

But when data from kafka receiver is published, only first created WebSocketSession receiveds it and all other WebSocketSessions do not receive the data

I am using spring-boot 2.6.3 with starter-tomcat

How to publish data to all the WebSocketSessions created
My Code:

Config for web socket handler

```<code>
@Configuration
@Slf4j
public class OneSecPollingWebSocketConfig
{
   private OneSecPollingWebSocketHandler oneSecPollingHandler;

   @Autowired
   public OneSecPollingWebSocketConfig(OneSecPollingWebSocketHandler oneSecPollingHandler)
   {
      this.oneSecPollingHandler = oneSecPollingHandler;
   }

   @Bean
   public HandlerMapping webSocketHandlerMapping()
   {
      log.info("onesecpolling websocket configured");
      Map<String, WebSocketHandler> handlerMap = new HashMap<>();
      handlerMap.put(WEB_SOCKET_ENDPOINT, oneSecPollingHandler);
      SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
      mapping.setUrlMap(handlerMap);
      mapping.setOrder(1);
      return mapping;
   }
}

</code>```

Code for WebSocket HAndler

```<code>
@Component
@Slf4j
public class OneSecPollingWebSocketHandler implements WebSocketHandler
{
   private ObjectMapper objectMapper;
   private OneSecPollingKafkaConsumerService oneSecPollingKafkaConsumerService;
   private Map<String, WebSocketSession> wsSessionsByUserSessionId = new HashMap<>();

   @Autowired
   public OneSecPollingWebSocketHandler(ObjectMapper objectMapper, OneSecPollingKafkaConsumerService oneSecPollingKafkaConsumerService)
   {
      this.objectMapper = objectMapper;
      this.oneSecPollingKafkaConsumerService = oneSecPollingKafkaConsumerService;
   }

   @Override
   public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Many<String> sink = Sinks.many().multicast().onBackpressureBuffer(Queues.SMALL_BUFFER_SIZE, false);
      wsSessionsByUserSessionId.put(getUserPollingSessionId(webSocketSession), webSocketSession);
      sinkSubscription(webSocketSession, sink);
      Mono<Void> output = webSocketSession.send(sink.asFlux().map(webSocketSession::textMessage)).doOnSubscribe(subscription ->
      {
      });
      return Mono.zip(webSocketSession.receive().then(), output).then();
   }

   public void sinkSubscription(WebSocketSession webSocketSession, Many<String> sink)
   {
      log.info("number of sessions; {}", wsSessionsByUserSessionId.size());
      oneSecPollingKafkaConsumerService.getTestTopicFlux().doOnNext(record ->
      {
         //log.info("record: {}", record);
         sink.tryEmitNext(record.value());
         record.receiverOffset().acknowledge();
      }).subscribe();
   }

   public String getOneSecPollingTopicRecord(ReceiverRecord<Integer, String> record, WebSocketSession webSocketSession)
   {
      String lastRecord = record.value();
      log.info("record to send: {} : webSocketSession: {}", record.value(), webSocketSession.getId());
      record.receiverOffset().acknowledge();
      return lastRecord;
   }

   public String getUserPollingSessionId(WebSocketSession webSocketSession)
   {
      UriTemplate template = new UriTemplate(WEB_SOCKET_ENDPOINT);
      URI uri = webSocketSession.getHandshakeInfo().getUri();
      Map<String, String> parameters = template.match(uri.getPath());
      String userPollingSessionId = parameters.get("userPollingSessionId");
      return userPollingSessionId;
   }
}

</code>```

Kafka Receiver

```<code>@Service
@Slf4j
public class OneSecPollingKafkaConsumerService
{
   private String bootStrapServers;

   @Autowired
   public OneSecPollingKafkaConsumerService(@Value("${bootstrap.servers}") String bootStrapServers)
   {
      this.bootStrapServers = bootStrapServers;
   }

   private ReceiverOptions<Integer, String> getRecceiverOPtions()
   {
      Map<String, Object> consumerProps = new HashMap<>();
      consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServers);
      //consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "reactive-consumer");
      consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "onesecpolling-group");
      consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
      consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
      //consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
      //consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

      ReceiverOptions<Integer, String> receiverOptions = ReceiverOptions
         .<Integer, String> create(consumerProps)
         .subscription(Collections.singleton("HighFrequencyPollingKPIsComputedValues"));

      return receiverOptions;
   }

   public Flux<ReceiverRecord<Integer, String>> getTestTopicFlux()
   {
      return createTopicCache();
   }

   private Flux<ReceiverRecord<Integer, String>> createTopicCache()
   {
      Flux<ReceiverRecord<Integer, String>> oneSecPollingMessagesFlux = KafkaReceiver.create(getRecceiverOPtions())
         .receive()
         .delayElements(Duration.ofMillis(500));
      return oneSecPollingMessagesFlux;
   }
}

</code>```

POM dependencies

```<code><dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <!--
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
      <groupId>io.projectreactor.kafka</groupId>
      <artifactId>reactor-kafka</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!-- This is breaking WebFlux
      <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>${springdoc.version}</version>
      </dependency>
      -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.projectreactor</groupId>
      <artifactId>reactor-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream</artifactId>
      <classifier>test-binder</classifier>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <!-- <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-test</artifactId>
      <scope>test</scope>
    </dependency> -->
  </dependencies>
</code>```

I also tried changing the handle(...) method definition in WebSocketHanlder to following, but still data from kafka is pushed to only one websocket session:

```<code>@Override
   public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive().then();
      Mono<Void> output = webSocketSession.send(oneSecPollingKafkaConsumerService.getTestTopicFlux().map(ReceiverRecord::value).map(webSocketSession::textMessage));
      return Mono.zip(input, output).then();
   }
</code>```

Also, I tried following:

```<code>public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive()
         .doOnSubscribe(subscribe -> log.info("sesseion created sessionId:{}:userId:{};sessionhash:{}",
            webSocketSession.getId(),
            getUserPollingSessionId(webSocketSession),
            webSocketSession.hashCode()))
         .then();
      Flux<String> source = oneSecPollingKafkaConsumerService.getTestTopicFlux().map(record -> getOneSecPollingTopicRecord(record, webSocketSession)).log();
      Mono<Void> output = webSocketSession.send(source.map(webSocketSession::textMessage)).log();
      return Mono.zip(input, output).then().log();
   }
</code>```

I enabled log() and got following output:

```<code>20:09:22.652 [http-nio-8080-exec-9] INFO  c.m.e.w.p.i.w.v.OneSecPollingWebSocketHandler - sesseion created sessionId:a:userId:124;sessionhash:1974799413
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.RefCount.41 - | onSubscribe([Fuseable] FluxRefCount.RefCountInner)
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.Map.42 - onSubscribe(FluxMap.MapSubscriber)
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.Map.42 - request(1)
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.RefCount.41 - | request(32)
20:09:22.659 [http-nio-8080-exec-9] INFO  reactor.Mono.FromPublisher.43 - onSubscribe(MonoNext.NextSubscriber)
20:09:22.659 [http-nio-8080-exec-9] INFO  reactor.Mono.FromPublisher.43 - request(unbounded)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Mono.IgnorePublisher.48 - onSubscribe(MonoIgnoreElements.IgnoreElementsSubscriber)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Mono.IgnorePublisher.48 - request(unbounded)
20:09:25.942 [http-nio-8080-exec-10] INFO  c.m.e.w.p.i.w.v.OneSecPollingWebSocketHandler - sesseion created sessionId:b:userId:123;sessionhash:1582184236
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.RefCount.45 - | onSubscribe([Fuseable] FluxRefCount.RefCountInner)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.Map.46 - onSubscribe(FluxMap.MapSubscriber)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.Map.46 - request(1)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.RefCount.45 - | request(32)
20:09:25.947 [http-nio-8080-exec-10] INFO  reactor.Mono.FromPublisher.47 - onSubscribe(MonoNext.NextSubscriber)
20:09:25.949 [http-nio-8080-exec-10] INFO  reactor.Mono.FromPublisher.47 - request(unbounded)
20:10:00.880 [reactive-kafka-onesecpolling-group-11] INFO  reactor.Flux.RefCount.41 - | onNext(ConsumerRecord(topic = HighFrequencyPollingKPIsComputedValues, partition = 0, leaderEpoch = null, offset = 474, CreateTime = 1644071999871, serialized key size = -1, serialized value size = 43, headers = RecordHeaders(headers = [], isReadOnly = false), key = null, value = {"greeting" : "Hello", "name" : "Prashant"}))
20:10:01.387 [parallel-5] INFO  reactor.Flux.Map.42 - onNext({"greeting" : "Hello", "name" : "Prashant"})
20:10:01.389 [parallel-5] INFO  reactor.Flux.Map.42 - request(1)
</code>```

Here we can see that we have 2 subscribers to reactor-kafka flux:

reactor.Flux.Map.42 - onSubscribe(FluxMap.MapSubscriber

reactor.Flux.Map.46 - onSubscribe(FluxMap.MapSubscriber)

but when data is read from kafka topic, it is received by only one subscriber:

reactor.Flux.Map.42 - onNext({"greeting" : "Hello", "name" :
"Prashant"})

Is it a bug in the Webflux API  itself ?

答:
I have found the issue and the solution.

Problem
The way I was using Flux (obtained from KafkaReceiver) in WebSocketHandler handle() method is not correct.
For each websocket session created from multiple client requests, handle method is get called. And so, multiple Flux objects for KafkaReceiver.create().receive() are created. One of the Flux reads data from KafkaReceiver but other flux objects failed to do so.

```<code>public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive()
         .doOnSubscribe(subscribe -> log.info("sesseion created sessionId:{}:userId:{};sessionhash:{}",
            webSocketSession.getId(),
            getUserPollingSessionId(webSocketSession),
            webSocketSession.hashCode()))
         .then();
      **Flux<String> source = oneSecPollingKafkaConsumerService.getTestTopicFlux()**.map(record -> getOneSecPollingTopicRecord(record, webSocketSession)).log();
      Mono<Void> output = webSocketSession.send(source.map(webSocketSession::textMessage)).log();
      return Mono.zip(input, output).then().log();
   }
</code>```

Solution
Make sure that only one Flux is created for
KafkaReceiver.create().receive(). One way to do so is to make Flux in the constructor of WebSocketHandler (or KAfkaCOnsumer class)

```<code>private final Flux<String> source;

   @Autowired
   public OneSecPollingWebSocketHandler(OneSecPollingKafkaConsumerService oneSecPollingKafkaConsumerService)
   {
      source = oneSecPollingKafkaConsumerService.getOneSecPollingTopicFlux().map(r -> getOneSecPollingTopicRecord(r));
   }

   @Override
   public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      // add usersession id as session attribute
      Mono<Void> input = getInputMessageMono(webSocketSession);
      Mono<Void> output = getOutputMessageMono(webSocketSession);
      return Mono.zip(input, output).then().log();
   }

   private Mono<Void> getOutputMessageMono(WebSocketSession webSocketSession)
   {
      Mono<Void> output = webSocketSession.send(source.map(webSocketSession::textMessage)).doOnError(err -> log.error(err.getMessage())).doOnTerminate(() ->
      {
         log.info("onesecpolling session terminated;{}", webSocketSession.getId());
      }).log();
      return output;
   }

   private Mono<Void> getInputMessageMono(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive().doOnSubscribe(subscribe ->
      {
         log.info("onesecpolling session created sessionId:{}:userId:{}", webSocketSession.getId(), getUserPollingSessionId(webSocketSession));
      }).then();
      return input;
   }

   private String getOneSecPollingTopicRecord(ReceiverRecord<Integer, String> record)
   {
      String lastRecord = record.value();
      record.receiverOffset().acknowledge();
      return lastRecord;
   }

   private String getUserPollingSessionId(WebSocketSession webSocketSession)
   {
      UriTemplate template = new UriTemplate(WEB_SOCKET_ENDPOINT);
      URI uri = webSocketSession.getHandshakeInfo().getUri();
      Map<String, String> parameters = template.match(uri.getPath());
      String userPollingSessionId = parameters.get(WEB_SOCKET_ENDPOINT_USERID_SUBPATH);
      return userPollingSessionId;
   }
</code>```

Body:
Following is the scenario:

I create a reactor kafka receiver

Data consumed from kafka receiver is published to a WebSocketHanlder

WebSocketHanlder is mapped to a URL using SimpleUrlHandlerMapping

URL pattern is api/v1/ws/{ID} and I expect multiple WebSocketSession to get created based on different ID used in URI which are managed by single WebSocketHanlder, which is actually happening

But when data from kafka receiver is published, only first created WebSocketSession receiveds it and all other WebSocketSessions do not receive the data

I am using spring-boot 2.6.3 with starter-tomcat

How to publish data to all the WebSocketSessions created
My Code:

Config for web socket handler

@Configuration
@Slf4j
public class OneSecPollingWebSocketConfig
{
   private OneSecPollingWebSocketHandler oneSecPollingHandler;

   @Autowired
   public OneSecPollingWebSocketConfig(OneSecPollingWebSocketHandler oneSecPollingHandler)
   {
      this.oneSecPollingHandler = oneSecPollingHandler;
   }

   @Bean
   public HandlerMapping webSocketHandlerMapping()
   {
      log.info("onesecpolling websocket configured");
      Map<String, WebSocketHandler> handlerMap = new HashMap<>();
      handlerMap.put(WEB_SOCKET_ENDPOINT, oneSecPollingHandler);
      SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
      mapping.setUrlMap(handlerMap);
      mapping.setOrder(1);
      return mapping;
   }
}

Code for WebSocket HAndler

@Component
@Slf4j
public class OneSecPollingWebSocketHandler implements WebSocketHandler
{
   private ObjectMapper objectMapper;
   private OneSecPollingKafkaConsumerService oneSecPollingKafkaConsumerService;
   private Map<String, WebSocketSession> wsSessionsByUserSessionId = new HashMap<>();

   @Autowired
   public OneSecPollingWebSocketHandler(ObjectMapper objectMapper, OneSecPollingKafkaConsumerService oneSecPollingKafkaConsumerService)
   {
      this.objectMapper = objectMapper;
      this.oneSecPollingKafkaConsumerService = oneSecPollingKafkaConsumerService;
   }

   @Override
   public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Many<String> sink = Sinks.many().multicast().onBackpressureBuffer(Queues.SMALL_BUFFER_SIZE, false);
      wsSessionsByUserSessionId.put(getUserPollingSessionId(webSocketSession), webSocketSession);
      sinkSubscription(webSocketSession, sink);
      Mono<Void> output = webSocketSession.send(sink.asFlux().map(webSocketSession::textMessage)).doOnSubscribe(subscription ->
      {
      });
      return Mono.zip(webSocketSession.receive().then(), output).then();
   }

   public void sinkSubscription(WebSocketSession webSocketSession, Many<String> sink)
   {
      log.info("number of sessions; {}", wsSessionsByUserSessionId.size());
      oneSecPollingKafkaConsumerService.getTestTopicFlux().doOnNext(record ->
      {
         //log.info("record: {}", record);
         sink.tryEmitNext(record.value());
         record.receiverOffset().acknowledge();
      }).subscribe();
   }

   public String getOneSecPollingTopicRecord(ReceiverRecord<Integer, String> record, WebSocketSession webSocketSession)
   {
      String lastRecord = record.value();
      log.info("record to send: {} : webSocketSession: {}", record.value(), webSocketSession.getId());
      record.receiverOffset().acknowledge();
      return lastRecord;
   }

   public String getUserPollingSessionId(WebSocketSession webSocketSession)
   {
      UriTemplate template = new UriTemplate(WEB_SOCKET_ENDPOINT);
      URI uri = webSocketSession.getHandshakeInfo().getUri();
      Map<String, String> parameters = template.match(uri.getPath());
      String userPollingSessionId = parameters.get("userPollingSessionId");
      return userPollingSessionId;
   }
}

Kafka Receiver

@Service
@Slf4j
public class OneSecPollingKafkaConsumerService
{
   private String bootStrapServers;

   @Autowired
   public OneSecPollingKafkaConsumerService(@Value("${bootstrap.servers}") String bootStrapServers)
   {
      this.bootStrapServers = bootStrapServers;
   }

   private ReceiverOptions<Integer, String> getRecceiverOPtions()
   {
      Map<String, Object> consumerProps = new HashMap<>();
      consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServers);
      //consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "reactive-consumer");
      consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "onesecpolling-group");
      consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
      consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
      //consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
      //consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

      ReceiverOptions<Integer, String> receiverOptions = ReceiverOptions
         .<Integer, String> create(consumerProps)
         .subscription(Collections.singleton("HighFrequencyPollingKPIsComputedValues"));

      return receiverOptions;
   }

   public Flux<ReceiverRecord<Integer, String>> getTestTopicFlux()
   {
      return createTopicCache();
   }

   private Flux<ReceiverRecord<Integer, String>> createTopicCache()
   {
      Flux<ReceiverRecord<Integer, String>> oneSecPollingMessagesFlux = KafkaReceiver.create(getRecceiverOPtions())
         .receive()
         .delayElements(Duration.ofMillis(500));
      return oneSecPollingMessagesFlux;
   }
}

POM dependencies

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
      <groupId>io.projectreactor.kafka</groupId>
      <artifactId>reactor-kafka</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream</artifactId>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.projectreactor</groupId>
      <artifactId>reactor-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream</artifactId>
      <classifier>test-binder</classifier>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>

  </dependencies>

I also tried changing the handle(...) method definition in WebSocketHanlder to following, but still data from kafka is pushed to only one websocket session:

@Override
   public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive().then();
      Mono<Void> output = webSocketSession.send(oneSecPollingKafkaConsumerService.getTestTopicFlux().map(ReceiverRecord::value).map(webSocketSession::textMessage));
      return Mono.zip(input, output).then();
   }

Also, I tried following:

public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive()
         .doOnSubscribe(subscribe -> log.info("sesseion created sessionId:{}:userId:{};sessionhash:{}",
            webSocketSession.getId(),
            getUserPollingSessionId(webSocketSession),
            webSocketSession.hashCode()))
         .then();
      Flux<String> source = oneSecPollingKafkaConsumerService.getTestTopicFlux().map(record -> getOneSecPollingTopicRecord(record, webSocketSession)).log();
      Mono<Void> output = webSocketSession.send(source.map(webSocketSession::textMessage)).log();
      return Mono.zip(input, output).then().log();
   }

I enabled log() and got following output:

20:09:22.652 [http-nio-8080-exec-9] INFO  c.m.e.w.p.i.w.v.OneSecPollingWebSocketHandler - sesseion created sessionId:a:userId:124;sessionhash:1974799413
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.RefCount.41 - | onSubscribe([Fuseable] FluxRefCount.RefCountInner)
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.Map.42 - onSubscribe(FluxMap.MapSubscriber)
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.Map.42 - request(1)
20:09:22.652 [http-nio-8080-exec-9] INFO  reactor.Flux.RefCount.41 - | request(32)
20:09:22.659 [http-nio-8080-exec-9] INFO  reactor.Mono.FromPublisher.43 - onSubscribe(MonoNext.NextSubscriber)
20:09:22.659 [http-nio-8080-exec-9] INFO  reactor.Mono.FromPublisher.43 - request(unbounded)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Mono.IgnorePublisher.48 - onSubscribe(MonoIgnoreElements.IgnoreElementsSubscriber)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Mono.IgnorePublisher.48 - request(unbounded)
20:09:25.942 [http-nio-8080-exec-10] INFO  c.m.e.w.p.i.w.v.OneSecPollingWebSocketHandler - sesseion created sessionId:b:userId:123;sessionhash:1582184236
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.RefCount.45 - | onSubscribe([Fuseable] FluxRefCount.RefCountInner)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.Map.46 - onSubscribe(FluxMap.MapSubscriber)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.Map.46 - request(1)
20:09:25.942 [http-nio-8080-exec-10] INFO  reactor.Flux.RefCount.45 - | request(32)
20:09:25.947 [http-nio-8080-exec-10] INFO  reactor.Mono.FromPublisher.47 - onSubscribe(MonoNext.NextSubscriber)
20:09:25.949 [http-nio-8080-exec-10] INFO  reactor.Mono.FromPublisher.47 - request(unbounded)
20:10:00.880 [reactive-kafka-onesecpolling-group-11] INFO  reactor.Flux.RefCount.41 - | onNext(ConsumerRecord(topic = HighFrequencyPollingKPIsComputedValues, partition = 0, leaderEpoch = null, offset = 474, CreateTime = 1644071999871, serialized key size = -1, serialized value size = 43, headers = RecordHeaders(headers = [], isReadOnly = false), key = null, value = {"greeting" : "Hello", "name" : "Prashant"}))
20:10:01.387 [parallel-5] INFO  reactor.Flux.Map.42 - onNext({"greeting" : "Hello", "name" : "Prashant"})
20:10:01.389 [parallel-5] INFO  reactor.Flux.Map.42 - request(1)

Here we can see that we have 2 subscribers to reactor-kafka flux:

reactor.Flux.Map.42 - onSubscribe(FluxMap.MapSubscriber

reactor.Flux.Map.46 - onSubscribe(FluxMap.MapSubscriber)

but when data is read from kafka topic, it is received by only one subscriber:

reactor.Flux.Map.42 - onNext({"greeting" : "Hello", "name" :
"Prashant"})

Is it a bug in the Webflux API  itself ?

Body:
I have found the issue and the solution.

Problem
The way I was using Flux (obtained from KafkaReceiver) in WebSocketHandler handle() method is not correct.
For each websocket session created from multiple client requests, handle method is get called. And so, multiple Flux objects for KafkaReceiver.create().receive() are created. One of the Flux reads data from KafkaReceiver but other flux objects failed to do so.

public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive()
         .doOnSubscribe(subscribe -> log.info("sesseion created sessionId:{}:userId:{};sessionhash:{}",
            webSocketSession.getId(),
            getUserPollingSessionId(webSocketSession),
            webSocketSession.hashCode()))
         .then();
      **Flux<String> source = oneSecPollingKafkaConsumerService.getTestTopicFlux()**.map(record -> getOneSecPollingTopicRecord(record, webSocketSession)).log();
      Mono<Void> output = webSocketSession.send(source.map(webSocketSession::textMessage)).log();
      return Mono.zip(input, output).then().log();
   }

Solution
Make sure that only one Flux is created for
KafkaReceiver.create().receive(). One way to do so is to make Flux in the constructor of WebSocketHandler (or KAfkaCOnsumer class)

private final Flux<String> source;

   @Autowired
   public OneSecPollingWebSocketHandler(OneSecPollingKafkaConsumerService oneSecPollingKafkaConsumerService)
   {
      source = oneSecPollingKafkaConsumerService.getOneSecPollingTopicFlux().map(r -> getOneSecPollingTopicRecord(r));
   }

   @Override
   public Mono<Void> handle(WebSocketSession webSocketSession)
   {
      // add usersession id as session attribute
      Mono<Void> input = getInputMessageMono(webSocketSession);
      Mono<Void> output = getOutputMessageMono(webSocketSession);
      return Mono.zip(input, output).then().log();
   }

   private Mono<Void> getOutputMessageMono(WebSocketSession webSocketSession)
   {
      Mono<Void> output = webSocketSession.send(source.map(webSocketSession::textMessage)).doOnError(err -> log.error(err.getMessage())).doOnTerminate(() ->
      {
         log.info("onesecpolling session terminated;{}", webSocketSession.getId());
      }).log();
      return output;
   }

   private Mono<Void> getInputMessageMono(WebSocketSession webSocketSession)
   {
      Mono<Void> input = webSocketSession.receive().doOnSubscribe(subscribe ->
      {
         log.info("onesecpolling session created sessionId:{}:userId:{}", webSocketSession.getId(), getUserPollingSessionId(webSocketSession));
      }).then();
      return input;
   }

   private String getOneSecPollingTopicRecord(ReceiverRecord<Integer, String> record)
   {
      String lastRecord = record.value();
      record.receiverOffset().acknowledge();
      return lastRecord;
   }

   private String getUserPollingSessionId(WebSocketSession webSocketSession)
   {
      UriTemplate template = new UriTemplate(WEB_SOCKET_ENDPOINT);
      URI uri = webSocketSession.getHandshakeInfo().getUri();
      Map<String, String> parameters = template.match(uri.getPath());
      String userPollingSessionId = parameters.get(WEB_SOCKET_ENDPOINT_USERID_SUBPATH);
      return userPollingSessionId;
   }


问:
How do I use an env file with GitHub Actions?
I have multiple environments (dev, qa, prod) and I'm using .env files to store secrets etc... Now I'm switching to GitHub Actions, and I want to use my .env files and declare them into the env section of the github actions yml.

But from what I've seen so far, it seems that I can not set a file path and I have to manually re-declare all variables.

How should I proceed as best practice?

答:
You can also use a dedicated github action from github-marketplace to create .env files.

Example usage:

```<code>name: Create envfile

on: [push]

jobs:

  create-envfile:

    runs-on: ubuntu-18.04

    steps:
    - name: Make envfile
      uses: SpicyPizza/create-envfile@v1
      with:
        envkey_DEBUG: false
        envkey_SOME_API_KEY: "123456abcdef"
        envkey_SECRET_KEY: ${{ secrets.SECRET_KEY }}
        file_name: .env
</code>```

Depending on your values defined for secrets in github repo, this will create a .env file like below:

```<code>DEBUG: false
SOME_API_KEY: "123456abcdef"
SECRET_KEY: password123
</code>```

More info: https://github.com/marketplace/actions/create-env-file

Body:
You can also use a dedicated github action from github-marketplace to create .env files.

Example usage:

name: Create envfile

on: [push]

jobs:

  create-envfile:

    runs-on: ubuntu-18.04

    steps:
    - name: Make envfile
      uses: SpicyPizza/create-envfile@v1
      with:
        envkey_DEBUG: false
        envkey_SOME_API_KEY: "123456abcdef"
        envkey_SECRET_KEY: ${{ secrets.SECRET_KEY }}
        file_name: .env

Depending on your values defined for secrets in github repo, this will create a .env file like below:

DEBUG: false
SOME_API_KEY: "123456abcdef"
SECRET_KEY: password123

More info: https://github.com/marketplace/actions/create-env-file


问:
IntelIJ copy line without selection
I was wondering if there is a way to just remove the selection when I copy a line by doing ctrl + c on a line

before: I just have my cursor in a line:

after: I just press ctrl + c

I dont like how I have to do an extra step to unselect, there must be a way to just remove the select without removing any functionality. Vscode has it working perfectly but I would love to have the same experience in IntelIJ

答:
You can simply use Ctrl+D to copy a complete line without selecting it.

More info in JetBrains Help

Title: IntelIJ copy line without selection


问:
facebook fql for retrieving photos returns empty list []
```<code>select object_id, aid, src_small from photo where owner='{0}' ; {0}-the id of the user.
</code>```

This query returns 0 records. Do you know why?

答:
There may be an issue with permissions. You may need to grant user_photos permission.

See here - http://developers.facebook.com/docs/authentication/permissions

ContentLicense: CC BY-SA 3.0

Body:
select object_id, aid, src_small from photo where owner='{0}' ; {0}-the id of the user.

This query returns 0 records. Do you know why?


问:
Find String out of String with Data in Python
I need to find a String out of String from an JSON data. I do have given an Data to search for the right string.
Here is what i have done so far:

```<code>description = "Range: 1 = RED_STRAWBERRYS, 2 = WHITE_STRAWBERRYS, 3 = PINK_RASPBERRY, 4 = BLUE_BERRY"
data = "4"
data_plus_one = "5"
msg = (description[description.find(str(data))+len(description[0:4]):description.rfind(", "+data_plus_one +" =")])
print(msg)
</code>```

It does work. If I search for RED_STRAWBERRYS I do have the data = 1. And I get it back. But if i look for the last element. In this case for BLUE_BERRY then I get "BLUE_BERR" back without the last Letter. Does someone now a better way than this solution?

答:
A regex approach to generate a dictionary with numbers as the keys and fruits as the values might work here:

description = "Range: 1 = RED_STRAWBERRYS, 2 = WHITE_STRAWBERRYS, 3 = PINK_RASPBERRY, 4 = BLUE_BERRY"
d = dict(re.findall(r'(\d+) = ([^,]+)', description))
print("one:   " + d["1"])  # one:   RED_STRAWBERRYS
print("three: " + d["3"])  # three: PINK_RASPBERRY
```

Body:
I need to find a String out of String from an JSON data. I do have given an Data to search for the right string.
Here is what i have done so far:

description = "Range: 1 = RED_STRAWBERRYS, 2 = WHITE_STRAWBERRYS, 3 = PINK_RASPBERRY, 4 = BLUE_BERRY"
data = "4"
data_plus_one = "5"
msg = (description[description.find(str(data))+len(description[0:4]):description.rfind(", "+data_plus_one +" =")])
print(msg)

It does work. If I search for RED_STRAWBERRYS I do have the data = 1. And I get it back. But if i look for the last element. In this case for BLUE_BERRY then I get "BLUE_BERR" back without the last Letter. Does someone now a better way than this solution?


问:
How to sum value in javascript array obj from specific search category to useState
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

```<code>const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]
</code>```

How can i interate arr to get this effect ?

```<code>const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)
</code>```

Thanks you for your help ;-)

答:
You can use a combination of filter to filter only the proper category, and then reduce to sum values

const [fit, setFit] = useState(
    arr.filter(f => f.category === "fit").reduce((acc, c) => acc + c.cost, 0)
)
```
<p>However, you'll need to do it for each state, which might be a little redondant, so I think it's best to have only one state, with a "category array" which you can map thru to create your state with X categories. Something like that</p>
<pre class="lang-js prettyprint-override"><code>const [state, setState] = useState(
    ['fit', 'fat', 'slim', 'test'].reduce((cats, currentCat) => ({
        ...cats,
        [currentCat]: arr.filter(f => f.category === currentCat).reduce((acc, c) => acc + c.cost, 0)
    }), {})
)
</code>```

So if you need to add categories, you just have to add them in your array, and you can access each costs using state.fit, state.fat,...

Body:
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]

How can i interate arr to get this effect ?

const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)

Thanks you for your help ;-)

Body:
You can use a combination of filter to filter only the proper category, and then reduce to sum values

const [fit, setFit] = useState(
    arr.filter(f => f.category === "fit").reduce((acc, c) => acc + c.cost, 0)
)

However, you'll need to do it for each state, which might be a little redondant, so I think it's best to have only one state, with a "category array" which you can map thru to create your state with X categories. Something like that

const [state, setState] = useState(
    ['fit', 'fat', 'slim', 'test'].reduce((cats, currentCat) => ({
        ...cats,
        [currentCat]: arr.filter(f => f.category === currentCat).reduce((acc, c) => acc + c.cost, 0)
    }), {})
)

So if you need to add categories, you just have to add them in your array, and you can access each costs using state.fit, state.fat,...


问:
Best way of message passing from GameLoop (Main loop) on iPhone
Does excessive message passing (function calling) from a game Loop which is scheduled at 60 Hz make game performance worse? In my gameLoop a lot of work needs to be performed. So which is the better way: writing everything in GameLoop function or splitting the work into several function and then calling them from gameLoop?</p>

答: Personally I think the best advice is to go for the clearest implementation, i.e., separating your code.  If you have performance issues, then profile to find the culprits - which will be much easier if your code is clear and then optimise.</p>


问:
How to extract data from Ng Multiselect dropdown to from group
I'm using Ng Multiselect Dropdown to select multiple data everything is working perfectly but I am facing issue with one thing and that is when users submits the data the data is uploaded but select option from drop down is stored like this [object] rather it should be stored with the selected option name

it is an issue with array decode can any one help me, below I have even shared the screenshot for the same

答:
I think it is all about how to iterate over your array of objects to view your objects properly, for example, if you have such data:

const ELEMENT_DATA: Element[] = [
  {
    checked: false,
    position: 1,
    item: [
      { item_id: 1, item_text: 'Item1' },
      { item_id: 2, item_text: 'Item2' },
      { item_id: 3, item_text: 'Item3' },
    ],
  },
  {
    checked: false,
    position: 2,
    item: [
      { item_id: 4, item_text: 'Item4' },
      { item_id: 5, item_text: 'Item5' },
      { item_id: 6, item_text: 'Item6' },
    ],
  },
];
```
<p>Then you can iterate over <code>item</code> array as follows:</p>
<pre class="lang-html prettyprint-override"><code><ng-container matColumnDef="item">
      <mat-header-cell *matHeaderCellDef> Item </mat-header-cell>
      <mat-cell *matCellDef="let element">
      <ng-container *ngFor="let i of element.item">
          {{i.item_id}} , {{i.item_text}}
          <br>
          <br>
      </ng-container>
      </mat-cell>
</ng-container>
</code>```

And these objects will be displayed like below:

Here is a working example:

https://stackblitz.com/edit/angular-hero-form-as-form-group-yzfwav?file=src%2Fapp%2Fapp.component.html

Body:
I think it is all about how to iterate over your array of objects to view your objects properly, for example, if you have such data:

const ELEMENT_DATA: Element[] = [
  {
    checked: false,
    position: 1,
    item: [
      { item_id: 1, item_text: 'Item1' },
      { item_id: 2, item_text: 'Item2' },
      { item_id: 3, item_text: 'Item3' },
    ],
  },
  {
    checked: false,
    position: 2,
    item: [
      { item_id: 4, item_text: 'Item4' },
      { item_id: 5, item_text: 'Item5' },
      { item_id: 6, item_text: 'Item6' },
    ],
  },
];

Then you can iterate over item array as follows:

<ng-container matColumnDef="item">
      <mat-header-cell *matHeaderCellDef> Item </mat-header-cell>
      <mat-cell *matCellDef="let element">
      <ng-container *ngFor="let i of element.item">
          {{i.item_id}} , {{i.item_text}}
          <br>
          <br>
      </ng-container>
      </mat-cell>
</ng-container>

And these objects will be displayed like below:

Here is a working example:

https://stackblitz.com/edit/angular-hero-form-as-form-group-yzfwav?file=src%2Fapp%2Fapp.component.html


问:
Returning the numbers in a list whose sum is a given target
```<code>input = x[1,2,4,6,3,9]
target = 6
</code>```

o/p:
the first number is 1 and the second number is 5

I came across this problem and I solved it using this code:

```<code>def search(a,b):
    for d in b:
        if a==d:
            m=True
            break
        else:
            m=False
    return m

x=[1,4,5,7,9,6,2]
target=int(raw_input("Enter the number:"))
for i in x:
    if i<target:
        pair=int(target)-int(i)
        in2=search(pair,x)
        if in2==True:
            print "the first number= %d the second number %d"%(i,pair)
            break
</code>```

How can I do this better or in a more efficient manner?

答:
Credit for idea: https://youtu.be/kVgy1GSDHG8 - "If you are stuck, throw a has map at it".

We can solve this in linear time using dictionaries. In the dictionary, use the number value as key, and its index as the value. That way, when iterating through, we can efficiently check if difference (target - current_number) is a number we have already iterated through.

x = [1, 4, 5, 7, 9, 6, 2]
target = 6

def getIndices(lst, target):
    """Return indices i,j such that lst[i] + lst[j] = target.

    Assumes solution exists"""
    indexDict = {}
    for i, num in enumerate(x):
        difference = target - num
        try:
            j = indexDict[difference]
            return i, j
        except KeyError:
            indexDict[num] = i

print(getIndices(x, target))
```

Body:
input = x[1,2,4,6,3,9]
target = 6

o/p:
the first number is 1 and the second number is 5

I came across this problem and I solved it using this code:

def search(a,b):
    for d in b:
        if a==d:
            m=True
            break
        else:
            m=False
    return m

x=[1,4,5,7,9,6,2]
target=int(raw_input("Enter the number:"))
for i in x:
    if i<target:
        pair=int(target)-int(i)
        in2=search(pair,x)
        if in2==True:
            print "the first number= %d the second number %d"%(i,pair)
            break

How can I do this better or in a more efficient manner?