问:
React: edit fields and send to DB only that data
I hope someone can help me solve this doubt. I'm trying to create a tool (Node + React) to quickly edit some data on the products of eCommerce (Prestashop in this particular case). It's my first project in React and I don't understand what I'm doing wrong. The table prints correctly and I've added a form to quickly edit the fields I want (product name, short description, description). Once edited there is a callback that updates the variable state (I made one per field, I guess it could be done better) and then there is an update button that should send the data to the backend. The problem is that I can't get the data from the right row. If I edit the fields of two different lines the update button sends only the last modified data. How can I fix this? Also, do you have any suggestions to make this thing better? Thanks</p>
```<code>import React, {useEffect, useState} from 'react'
import { EditText, EditTextarea } from 'react-edit-text'

function Catalogue() {
  const [backendData, setBackendData] = useState([])
  const [prname, setPrname] = useState("")
  const [shortdes, setShortdes] = useState("")
  const [desc, setDesc] = useState("")

  const saveName = ({ name, value, previousValue }) => {
    setPrname(value)
    alert(name + ' saved as: ' + value)
  };
  const saveShort = ({name, value, previousValue}) => {
    setShortdes(value)
    alert(name + ' saved as: ' + value)
  }
  const saveDesc = ({name, value, previousValue}) => {
    setDesc(value)
    alert(name + ' saved as: ' + value)
  }
  const updateData = (name, short, desc, productId) => {
    if(name || short || desc) {
      console.log( productId + " Product Name: " + name + " Short Description: " + short + " Long Description: " + desc)
      let item = {name, short, desc, productId}
      console.log(item)
    }
  }
    useEffect(()=>{ fetch("/api").then( response => response.json() ).then( data => { setBackendData(data) } ) },
    [])
return(
  <>
      <table>
      <thead>
          <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Description</th>
          </tr>
      </thead>
      <tbody>
      {(typeof backendData.products === 'undefined') ? (
      <tr><td>Loading...</td></tr>
    ): (
      backendData.products.map((product, i) => (
          <tr key={i}>
            <td className="product_id">{product.id_product}</td>
            <td className="product_name">
              <EditText
                  name={product.name}
                  defaultValue={product.name}
                  placeholder='Product Name'
                  onSave={saveName}
                  />
            </td>
            <td className="product_short_description">
                    <EditTextarea
                        rows={8}
                        name={product.description_short}
                        defaultValue={product.description_short}
                        placeholder='Product Short Description'
                        onSave={saveShort}
                    />
            </td>
            <td className="product_description">
                      <EditTextarea
                        rows={8}
                        name={product.description}
                        defaultValue={product.description}
                        placeholder='Product Description'
                        onSave={saveDesc}
                    />
            </td>
            <td>
              <button className="btn-Update" onClick={() => updateData(prname, shortdes, desc, product.id_product)}>Update</button>
            </td>
          </tr>
      ))
    )}
    </tbody>
  </table>
</>
)
}

export default Catalogue```
</code>```

Body:
I hope someone can help me solve this doubt. I'm trying to create a tool (Node + React) to quickly edit some data on the products of eCommerce (Prestashop in this particular case). It's my first project in React and I don't understand what I'm doing wrong. The table prints correctly and I've added a form to quickly edit the fields I want (product name, short description, description). Once edited there is a callback that updates the variable state (I made one per field, I guess it could be done better) and then there is an update button that should send the data to the backend. The problem is that I can't get the data from the right row. If I edit the fields of two different lines the update button sends only the last modified data. How can I fix this? Also, do you have any suggestions to make this thing better? Thanks

import React, {useEffect, useState} from 'react'
import { EditText, EditTextarea } from 'react-edit-text'

function Catalogue() {
  const [backendData, setBackendData] = useState([])
  const [prname, setPrname] = useState("")
  const [shortdes, setShortdes] = useState("")
  const [desc, setDesc] = useState("")

  const saveName = ({ name, value, previousValue }) => {
    setPrname(value)
    alert(name + ' saved as: ' + value)
  };
  const saveShort = ({name, value, previousValue}) => {
    setShortdes(value)
    alert(name + ' saved as: ' + value)
  }
  const saveDesc = ({name, value, previousValue}) => {
    setDesc(value)
    alert(name + ' saved as: ' + value)
  }
  const updateData = (name, short, desc, productId) => {
    if(name || short || desc) {
      console.log( productId + " Product Name: " + name + " Short Description: " + short + " Long Description: " + desc)
      let item = {name, short, desc, productId}
      console.log(item)
    }
  }
    useEffect(()=>{ fetch("/api").then( response => response.json() ).then( data => { setBackendData(data) } ) },
    [])
return(
  <>

              ID
              Name
              Description

      {(typeof backendData.products === 'undefined') ? (

Loading...

    ): (
      backendData.products.map((product, i) => (

            {product.id_product}

              <EditText
                  name={product.name}
                  defaultValue={product.name}
                  placeholder='Product Name'
                  onSave={saveName}
                  />

                    <EditTextarea
                        rows={8}
                        name={product.description_short}
                        defaultValue={product.description_short}
                        placeholder='Product Short Description'
                        onSave={saveShort}
                    />

                      <EditTextarea
                        rows={8}
                        name={product.description}
                        defaultValue={product.description}
                        placeholder='Product Description'
                        onSave={saveDesc}
                    />

              <button className="btn-Update" onClick={() => updateData(prname, shortdes, desc, product.id_product)}>Update</button>

      ))
    )}

</>
)
}

export default Catalogue```


来源: stackexchange

问:
Maven Build error while using pom version 3.0.1 on my Spring boot Java project on IntelliJ
I am using maven pom version 3.0.1 and while building getting errors as below. I installed the certificate also in VDI of my java folder. Can you please help on this?

```<code>Cannot resolve plugin org.apache.maven.plugins:maven-compiler-plugin:3.10.1

Cannot resolve plugin org.apache.maven.plugins:maven-surefire-plugin:2.22.2

Cannot resolve plugin org.apache.maven.plugins:maven-deploy-plugin:2.8.2

Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:3.2.0

Cannot resolve plugin org.apache.maven.plugins:maven-resources-plugin:3.3.0

Cannot resolve plugin org.apache.maven.plugins:maven-jar-plugin:3.3.0

Cannot resolve plugin org.apache.maven.plugins:maven-install-plugin:3.0.1

Cannot resolve plugin org.apache.maven.plugins:maven-site-plugin:3.3

Cannot resolve plugin org.apache.maven.plugins:maven-compiler-plugin:3.8.0

Cannot resolve plugin org.springframework.boot:spring-boot-maven-plugin:2.1.4.RELEASE

Cannot resolve plugin org.apache.maven.plugins:maven-surefire-plugin:2.22.2

Cannot resolve plugin org.apache.maven.plugins:maven-deploy-plugin:2.8.2

Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:3.1.0

Cannot resolve plugin org.apache.maven.plugins:maven-resources-plugin:3.1.0

Cannot resolve plugin org.apache.maven.plugins:maven-jar-plugin:3.1.1

Cannot resolve plugin org.apache.maven.plugins:maven-install-plugin:2.5.2

Cannot resolve plugin org.apache.maven.plugins:maven-site-plugin:3.7.1
</code>```

I java spring boot project with the pom version 3.0.1 and i installed the certificate also in VDI of my java folder. Still same issue on my IntelliJ IDE.

Could you please help on this?

ContentLicense: CC BY-SA 4.0

Body:
I am using maven pom version 3.0.1 and while building getting errors as below. I installed the certificate also in VDI of my java folder. Can you please help on this?

Cannot resolve plugin org.apache.maven.plugins:maven-compiler-plugin:3.10.1

Cannot resolve plugin org.apache.maven.plugins:maven-surefire-plugin:2.22.2

Cannot resolve plugin org.apache.maven.plugins:maven-deploy-plugin:2.8.2

Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:3.2.0

Cannot resolve plugin org.apache.maven.plugins:maven-resources-plugin:3.3.0

Cannot resolve plugin org.apache.maven.plugins:maven-jar-plugin:3.3.0

Cannot resolve plugin org.apache.maven.plugins:maven-install-plugin:3.0.1

Cannot resolve plugin org.apache.maven.plugins:maven-site-plugin:3.3

Cannot resolve plugin org.apache.maven.plugins:maven-compiler-plugin:3.8.0

Cannot resolve plugin org.springframework.boot:spring-boot-maven-plugin:2.1.4.RELEASE

Cannot resolve plugin org.apache.maven.plugins:maven-surefire-plugin:2.22.2

Cannot resolve plugin org.apache.maven.plugins:maven-deploy-plugin:2.8.2

Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:3.1.0

Cannot resolve plugin org.apache.maven.plugins:maven-resources-plugin:3.1.0

Cannot resolve plugin org.apache.maven.plugins:maven-jar-plugin:3.1.1

Cannot resolve plugin org.apache.maven.plugins:maven-install-plugin:2.5.2

Cannot resolve plugin org.apache.maven.plugins:maven-site-plugin:3.7.1

I java spring boot project with the pom version 3.0.1 and i installed the certificate also in VDI of my java folder. Still same issue on my IntelliJ IDE.

Could you please help on this?


问:
Attaching to proccess in vsCode debug is bugged
When I attach to my proccess via vscode debug It just stuck and I can not to terminate it, can not to reload it / pause / stop, everything. The breakpoints is not working, the debug will not stop on a breakpoint when should...
I can't start another debug process, can't attach to another one. It's just stuck and I have only one option - close vsCode
The problem is only with attach proccess in debug. Everything else working fine...
Buttons aren't working, nothing happens while I turn off vsCode completely

Tried to change variables in launch.json etc. Nothing changes
All worked fine in evening last month, next day the debugger is dead like that.
My launch.json setting for attaching


问:
Cannot find sun.misc.URLClassPath after upgrading JAVA JDK8 to JDK11
I have a method to unload *.jar files at runtime using JAVA JDK 8 below. Then, I upgrade my app to use JAVA JDK 11, and it does not recognize sun.misc.URLClassPath.
What class in JDK 11 can be replaced it? I search on the Internet, but I have not found the answer yet.

```<code>import sun.misc.URLClassPath;

public static boolean unloadJar(String jarFile, ClassLoader classLoader) {
        try {
            if (classLoader instanceof URLClassLoader) {
                URLClassPath ucp = (URLClassPath)getField(classLoader, "ucp", URLClassLoader.class);
                ArrayList<URL> path = (ArrayList<URL>)getField(ucp, "path");
                ArrayList<?> loaders = (ArrayList<?>)getField(ucp, "loaders");
                boolean isRemovedFromPath = path.removeIf(p -> p.getFile().endsWith(jarFile));
                boolean isRemovedFromLoaders = loaders.removeIf(l -> {
                    try {
                        URL csu = (URL)getField(l, "csu");
                        return csu.getFile().endsWith(jarFile);
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        return false;
                    }
                });

                return isRemovedFromPath && isRemovedFromLoaders;
            } else {
                String msg = String.format("Class loader type is mismatched. Required: %s, actual: %s",
                        classLoader.getClass().getName(), URLClassLoader.class.getName());
                logger.debug(msg);
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
</code>```

Body:
I have a method to unload *.jar files at runtime using JAVA JDK 8 below. Then, I upgrade my app to use JAVA JDK 11, and it does not recognize sun.misc.URLClassPath.
What class in JDK 11 can be replaced it? I search on the Internet, but I have not found the answer yet.

import sun.misc.URLClassPath;

public static boolean unloadJar(String jarFile, ClassLoader classLoader) {
        try {
            if (classLoader instanceof URLClassLoader) {
                URLClassPath ucp = (URLClassPath)getField(classLoader, "ucp", URLClassLoader.class);
                ArrayList<URL> path = (ArrayList<URL>)getField(ucp, "path");
                ArrayList<?> loaders = (ArrayList<?>)getField(ucp, "loaders");
                boolean isRemovedFromPath = path.removeIf(p -> p.getFile().endsWith(jarFile));
                boolean isRemovedFromLoaders = loaders.removeIf(l -> {
                    try {
                        URL csu = (URL)getField(l, "csu");
                        return csu.getFile().endsWith(jarFile);
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        return false;
                    }
                });

                return isRemovedFromPath && isRemovedFromLoaders;
            } else {
                String msg = String.format("Class loader type is mismatched. Required: %s, actual: %s",
                        classLoader.getClass().getName(), URLClassLoader.class.getName());
                logger.debug(msg);
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }


问:
GNU Linker no longer overrides Weak symbols?
When trying to compile and link two c modules with GCC, both containing a global variable with the same name, I get an error of multiple definitions.
Despite the fact that both are so-called weak symbols.

A code example:

I've tried to compile and link the 2 following c modules:

// b1.c
int x;
int main() {}
```
<pre class="lang-c prettyprint-override"><code>// b2.c
int x;
</code>```

Now, supposedly, the var x in both files, should be a weak symbol.
So when linking, both should reference the same value.

But, for some reason, I get the following error:

$ gcc b1.c b2.c
/usr/bin/ld: /tmp/ccCP4DM3.o:(.bss+0x0): multiple definition of `x`; /tmp/ccN4Bd4O.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

$ gcc --version
gcc 11.3.0
$ ld --version
GNU ld 2.38
```

So, did something change? Because according to the "Computer Systems
A Programmer’s Perspective" section 7.6, it should compile and link just fine using gcc without any special flags.

Body:
When trying to compile and link two c modules with GCC, both containing a global variable with the same name, I get an error of multiple definitions.
Despite the fact that both are so-called weak symbols.

A code example:

I've tried to compile and link the 2 following c modules:

// b1.c
int x;
int main() {}

// b2.c
int x;

Now, supposedly, the var x in both files, should be a weak symbol.
So when linking, both should reference the same value.

But, for some reason, I get the following error:

$ gcc b1.c b2.c
/usr/bin/ld: /tmp/ccCP4DM3.o:(.bss+0x0): multiple definition of `x`; /tmp/ccN4Bd4O.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

$ gcc --version
gcc 11.3.0
$ ld --version
GNU ld 2.38

So, did something change? Because according to the "Computer Systems
A Programmer’s Perspective" section 7.6, it should compile and link just fine using gcc without any special flags.


问:
Package nodejs module as a jar
Most of my projects are built in Java and there was one set of requirement which we created using using NodeJS. Node JS had better options in buiding that utility and that is the reason we went with NodeJS.

Now I want to use that utility in all other java based projects as a dependent jar rather than invoking this Node JS service.

Is it possible to bundle this Node JS module into a jar and add it as a dependency in other java projects?

Title: Package nodejs module as a jar


Title: How to make this to data frame?

Body:
I am using python and I am trying to change this to dataframe but the length of the dictionary are different.
Do you have any ideas? The length of keys (0-6 in total) present are different in each row.

0             {1: 0.14428478, 3: 0.3088169, 5: 0.54362816}
1        {0: 0.41822478, 2: 0.081520624, 3: 0.40189278,...
2                                           {3: 0.9927109}
3                            {0: 0.07826376, 3: 0.9162877}
4        {0: 0.022929467, 1: 0.0127365505, 2: 0.8355256...
                               ...
59834                      {1: 0.93473625, 5: 0.055679787}
59835          {1: 0.72145665, 3: 0.022041071, 5: 0.25396}
59836    {0: 0.01922486, 1: 0.019249884, 2: 0.5345934, ...
59837    {0: 0.014184893, 1: 0.23436697, 2: 0.58155864,...
59838    {0: 0.013977169, 1: 0.24653174, 2: 0.60093427,...

I would like get the codes of python.


问:
Rendering template that is provided by server
Our project architect decided that they want to have html-Templates for a guide book for our users persisted in our database for version management and other reasons.
Now they expect me to fetch those templates whenever a user opens the guide book inside our application and display it as a responsive webpage.

So far so good. The problem arises when they told me to include dozens of features and s in this guide book.

So I need to fetch templates which contain non native component-tags and manipulate those to do some in logic stuff (like handling MatDialogs for example) and display these.

When injecting these via [innerHTML] this obviously breaks since the templates are not compiled by angular and therefore tags like <mat-icon> cannot be resolved. In addition all event handlers like onclick an stuff are erased by the Angular Sanitizer anyway (thank gooogle/god for that).

To conclude:
Is there any chance/hope that this all is achievable or do I need to confront out architect?


问:
how do i send image files to server
The method i used is to send an image to a chatbot and enter the server.

I want to send the image to the server without going through the chatbot.

I'm encoding the image file into base64 and sending it to the same port, but 400 or 500 errors keep coming out.

I was going to send it this way.

```<code>import os
import glob
import requests
import base64

folder_path = "./images"
image_files = glob.glob(os.path.join(folder_path, "*.jpg")) +
glob.glob(os.path.join(folder_path, "*.jpeg")) +
glob.glob(os.path.join(folder_path, "*.png"))

url="http://000000000/"

headers = {'Content-type':'application/json; charset=utf-8'}

for file_path in image_files:
with open(file_path, "rb") as file:
    file_content = file.read()
    encoded_file = base64.b64encode(file_content).decode()
    data = {"file": (os.path.basename(file_path), encoded_file)}
    r = requests.post(url, files=data, headers=headers)
    print(f'{os.path.basename(file_path)} sent with status code {r.status_code}')
</code>```

error message is :

requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionAbortedError(10053

it is using ocr system which is in server

since i have to change the method to send imgae files. i wrote those codes but it's not working

Title: how do i send image files to server

Body:
The method i used is to send an image to a chatbot and enter the server.

I want to send the image to the server without going through the chatbot.

I'm encoding the image file into base64 and sending it to the same port, but 400 or 500 errors keep coming out.

I was going to send it this way.

import os
import glob
import requests
import base64

folder_path = "./images"
image_files = glob.glob(os.path.join(folder_path, "*.jpg")) +
glob.glob(os.path.join(folder_path, "*.jpeg")) +
glob.glob(os.path.join(folder_path, "*.png"))

url="http://000000000/"

headers = {'Content-type':'application/json; charset=utf-8'}

for file_path in image_files:
with open(file_path, "rb") as file:
    file_content = file.read()
    encoded_file = base64.b64encode(file_content).decode()
    data = {"file": (os.path.basename(file_path), encoded_file)}
    r = requests.post(url, files=data, headers=headers)
    print(f'{os.path.basename(file_path)} sent with status code {r.status_code}')

error message is :

requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionAbortedError(10053

it is using ocr system which is in server

since i have to change the method to send imgae files. i wrote those codes but it's not working


问:
Python3- what's the proper way to connect to database across different methods?
Need help please.
I want to create 2 additional functions that will insert into the database each table instead of in one function as below in def insert_to_db(self).
Is the correct way to create 2 additional functions or to leave it as it is or any other way?
If it's to create another function how do I pass the db and cursor to the new functions?

main.py

```<code>class ConfigMain:
  def __init__(self, filepath):
        env_params = get_env_params()
        self.db = connect_to_db(user=env_params.user_name,
                                password=env_params.password,
                                host=env_params.host,
                                port=env_params.port,
                                database=env_params.database)
        self.filepath = filepath
</code>```

ConfigMain.py

```<code> from main import ConfigMain
    import openpyxl
    import mariadb
    import logging

    class DBConfig(ConfigMain):
        def insert_to_db(self):
           conn = self.db[0]
            cursor = self.db[1]
             wb = openpyxl.load_workbook(filename=self.filepath, data_only=True)
            s = 0
            file_sheets = wb.sheetnames
            for s in range(len(file_sheets)):
                # order_invoice Sheet
                if file_sheets[s] == 'Sheet1':
                    # table = 'order_invoice'
                    num_rows_inserted = 0
                    num_rows_inserted_item = 0
                    try:
                        wb.active = s
                        sheet = wb.active
                         row_count = sheet.max_row
                        column_count = sheet.max_column
                        for r in range(2, row_count + 1):
                             order_invoice_id = order_invoice_id.replace(" ", "")
                              billing_cycle_id = str(billing_year) + str(billing_month)
                             # Assign values from each row
                            values = (order_invoice_id, billing_cycle_id)
                            table = 'order_invoice'
                            query = """INSERT INTO """ + table + """(order_invoice_id, billing_cycle_id) VALUES  (%s, %s) """
                            # Execute sql Query
                            cursor.execute(query, values)
                            num_rows_inserted = num_rows_inserted + cursor.rowcount

                            table = 'order_item'
                            # transformations
                            order_invoice_id = order_invoice_id.replace(" ", "")
                            order_invoice_item_id = str(order_invoice_id) + str(order_invoice_item_id)

                            #             # Assign values from each row
                            values = ( order_invoice_item_id, order_invoice_id)
                           query = """INSERT INTO """ + table + """(order_invoice_item_id,
                            order_invoice_id) VALUES (%s,%s ) """
                           # Execute sql Query
                            cursor.execute(query, values)

                    except mariadb.IntegrityError as e:
                        print(f"{e} - for table '{table}' ")
                        raise

                    except mariadb.DataError as e:
                        print(f"{e} - for table '{table}' ")
                        raise

</code>```

Thank you!

Body:
Need help please.
I want to create 2 additional functions that will insert into the database each table instead of in one function as below in def insert_to_db(self).
Is the correct way to create 2 additional functions or to leave it as it is or any other way?
If it's to create another function how do I pass the db and cursor to the new functions?

main.py

class ConfigMain:
  def __init__(self, filepath):
        env_params = get_env_params()
        self.db = connect_to_db(user=env_params.user_name,
                                password=env_params.password,
                                host=env_params.host,
                                port=env_params.port,
                                database=env_params.database)
        self.filepath = filepath

ConfigMain.py

 from main import ConfigMain
    import openpyxl
    import mariadb
    import logging

    class DBConfig(ConfigMain):
        def insert_to_db(self):
           conn = self.db[0]
            cursor = self.db[1]
             wb = openpyxl.load_workbook(filename=self.filepath, data_only=True)
            s = 0
            file_sheets = wb.sheetnames
            for s in range(len(file_sheets)):
                # order_invoice Sheet
                if file_sheets[s] == 'Sheet1':
                    # table = 'order_invoice'
                    num_rows_inserted = 0
                    num_rows_inserted_item = 0
                    try:
                        wb.active = s
                        sheet = wb.active
                         row_count = sheet.max_row
                        column_count = sheet.max_column
                        for r in range(2, row_count + 1):
                             order_invoice_id = order_invoice_id.replace(" ", "")
                              billing_cycle_id = str(billing_year) + str(billing_month)
                             # Assign values from each row
                            values = (order_invoice_id, billing_cycle_id)
                            table = 'order_invoice'
                            query = """INSERT INTO """ + table + """(order_invoice_id, billing_cycle_id) VALUES  (%s, %s) """
                            # Execute sql Query
                            cursor.execute(query, values)
                            num_rows_inserted = num_rows_inserted + cursor.rowcount

                            table = 'order_item'
                            # transformations
                            order_invoice_id = order_invoice_id.replace(" ", "")
                            order_invoice_item_id = str(order_invoice_id) + str(order_invoice_item_id)

                            #             # Assign values from each row
                            values = ( order_invoice_item_id, order_invoice_id)
                           query = """INSERT INTO """ + table + """(order_invoice_item_id,
                            order_invoice_id) VALUES (%s,%s ) """
                           # Execute sql Query
                            cursor.execute(query, values)

                    except mariadb.IntegrityError as e:
                        print(f"{e} - for table '{table}' ")
                        raise

                    except mariadb.DataError as e:
                        print(f"{e} - for table '{table}' ")
                        raise

Thank you!


问:
How to sum row values base on dynamic conditions
I have a dataframe like this:

I want to get the sum of each colum [Gliders, Helicopters, Jet engines, Piston engines, Turbo-propellers] for every state each year. So at the end I will get for each REF_DATE I will get only one row for each different state.

Ex: For REF_DATE=2012 if there are 23 states I will get 23 rows with the same REF_DATE (2012), and so on for each REF_DATE.

The condition should be something like:

```<code>if((REF_DATE==REF_DATE)&&(State==State)):
  sum(Gliders)
  sum(Helicopters)
  sum(...)
</code>```

It will look something like this:

As @MattPitkin pointed, tt works fine with groupby, the answer was:

```<code>df_states = df_ap.groupby(['REF_DATE', 'State']).sum()
</code>```

Body:
I have a dataframe like this:

I want to get the sum of each colum [Gliders, Helicopters, Jet engines, Piston engines, Turbo-propellers] for every state each year. So at the end I will get for each REF_DATE I will get only one row for each different state.

Ex: For REF_DATE=2012 if there are 23 states I will get 23 rows with the same REF_DATE (2012), and so on for each REF_DATE.

The condition should be something like:

if((REF_DATE==REF_DATE)&&(State==State)):
  sum(Gliders)
  sum(Helicopters)
  sum(...)

It will look something like this:

As @MattPitkin pointed, tt works fine with groupby, the answer was:

df_states = df_ap.groupby(['REF_DATE', 'State']).sum()


问:
My Firebase notification service only work with Debugger in Android
I am developing and android applications that implement a firebase notification service
as developing proccess i work with debugger in all the working flow but i just realize than
when i run the application with the "run" button instead of debug button or i install the apk
in a device, the notification are not received.

All the research about the notification service dont explaind nothing about this problem
on android, only on IOS.

I check the configuration of the pushlauncher application, the token, the notice's id. But i dont know if is need any aditional setting in google cloud.


问:
My Dataset import returns with an error code
I tried importing a dataset and it return with this error.

Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
there is no package called ‘cli’

what package do i need to install?

my code read this

personality <- read_xlsx("Downloads/SMP84.xlsx")


问:
JavaScript can't check MDL checkbox
When I click on "Check", only the normal checkbox gets checked and not the MDL one (as shown in the image below). Would someone know why this is happening?

function check() {
  document.getElementById('mdl').checked = true;
  document.getElementById('normal').checked = true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-deep_purple.min.css" />
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="mdl">
  <input type="checkbox" id="mdl" class="mdl-checkbox__input">
  <span class="mdl-checkbox__label">MDL</span>
</label>
<input type="checkbox" id="normal" name="normal">
<label for="normal"> Normal</label><br>
<button type="button" class="mdl-button mdl-js-button mdl-button--raised" onclick="check()">Check</button></code>```

Title: JavaScript can't check MDL checkbox

Body:
When I click on "Check", only the normal checkbox gets checked and not the MDL one (as shown in the image below). Would someone know why this is happening?

function check() {
  document.getElementById('mdl').checked = true;
  document.getElementById('normal').checked = true;
}

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.blue_grey-deep_purple.min.css" />

  <input type="checkbox" id="mdl" class="mdl-checkbox__input">
  MDL

<input type="checkbox" id="normal" name="normal">
 Normal

<button type="button" class="mdl-button mdl-js-button mdl-button--raised" onclick="check()">Check</button>


问:
Need help on how to do callback in Angular
```<code>  async getExample(value: string) {
    // this must be done first
    if (this.componentRef) {
      this.componentRef.location.nativeElement.classList.add('fadeMeOut');
    }
    // this must be done second
    switch (value) {
      case this.tag[0]: {
        await this.getAlbum();
        break;
      }
      default: {
        //statements;
        break;
      }
    }
  }
</code>```

I would like to use callback feature to fix the problem but I don't know how.
basically, I would like to get the first part done completely and it moves on to the second part.

The logic is to call the first part and callback the second part.
I appreciate very much for any helps.
Thank you.

Body:
  async getExample(value: string) {
    // this must be done first
    if (this.componentRef) {
      this.componentRef.location.nativeElement.classList.add('fadeMeOut');
    }
    // this must be done second
    switch (value) {
      case this.tag[0]: {
        await this.getAlbum();
        break;
      }
      default: {
        //statements;
        break;
      }
    }
  }

I would like to use callback feature to fix the problem but I don't know how.
basically, I would like to get the first part done completely and it moves on to the second part.

The logic is to call the first part and callback the second part.
I appreciate very much for any helps.
Thank you.


问:
PHP: openssl_private_decrypt: key parameter is not a authentic private key
Objective:My Requirement is to create a RSA public and private key to encrypt and decrypt a string.

Code:

```<code>openssl_public_encrypt($mobiles, $encryptedmob, $PK );
$Crypted=openssl_private_decrypt($encrypteds,$Decrypted,$PK2);
</code>```

Working: I succeed to encrypt data using public key and Decrypt data using private key in same php page.

Not working: I am unable to encrypt data using public key and Decrypt data using private key in different php page

Error: openssl_private_decrypt(): key parameter is not a valid private key.

I am able to encrypt data using public key and Decrypt data that is coming from database using private key in same php page,I am not able to encrypt data  using public key and Decrypt data that is coming from database using private key in different php page.

Body:
Objective:My Requirement is to create a RSA public and private key to encrypt and decrypt a string.

Code:

openssl_public_encrypt($mobiles, $encryptedmob, $PK );
$Crypted=openssl_private_decrypt($encrypteds,$Decrypted,$PK2);

Working: I succeed to encrypt data using public key and Decrypt data using private key in same php page.

Not working: I am unable to encrypt data using public key and Decrypt data using private key in different php page

Error: openssl_private_decrypt(): key parameter is not a valid private key.

I am able to encrypt data using public key and Decrypt data that is coming from database using private key in same php page,I am not able to encrypt data  using public key and Decrypt data that is coming from database using private key in different php page.


问:
How can I update the mp3 file in vue plyr component
how can i force a reload of the componente when i change the language on the page in a floater. I tried to use :key="store.state.language", but with each language change, the old language remains, but without the global css style for plyr

Is there a function to do this?

```<code><vue-plyr :options="optionsAudio" ref="vplyraudio2" @play="vPlayCheck('audio2')" >
        <audio controls crossorigin playsinline>
              <source
                   :src="'/mp3/' + audiobasename' + '_' + store.state.language + '.mp3'"
                   type="audio/mp3"
              />
        </audio>
</vue-plyr>
</code>```

heres a screenshot after a few language changes:

Body:
how can i force a reload of the componente when i change the language on the page in a floater. I tried to use :key="store.state.language", but with each language change, the old language remains, but without the global css style for plyr

Is there a function to do this?

<vue-plyr :options="optionsAudio" ref="vplyraudio2" @play="vPlayCheck('audio2')" >
        <audio controls crossorigin playsinline>
              <source
                   :src="'/mp3/' + audiobasename' + '_' + store.state.language + '.mp3'"
                   type="audio/mp3"
              />
        </audio>
</vue-plyr>

heres a screenshot after a few language changes:


问:
How to prune a pyspark dataframe from the rows that meet certain conditions
I am pretty new in pyspark, so any help is appreciated. I am trying iterate through a pyspark Dataframe, and filter it out from the rows that meet certain rules.

The Dataframe looks like this:

```<code>root
 |-- id: long (nullable = true)
 |-- email: string (nullable = true)
 |-- status: string (nullable = true)
 |-- foo: string (nullable = true)
 |-- bar: decimal(36,16) (nullable = true)
 |-- foobar: decimal(36,16) (nullable = true)
 |-- decision: string (nullable = true)
 |-- spam: string (nullable = true)
 |-- foobarfoo: decimal(36,16) (nullable = true)
 |-- shop: long (nullable = true)
 |-- dt: timestamp (nullable = true)
</code>```

This is what I could come up so far, but this does not accomplish the task:

```<code>def rules_check(arow,alist):
    for i in alist:
        rules_1 = [i['shop'] == arow['shop'],
                   i['email'] == arow['email'],
                   ((i['dt'] - arow['dt']).days <=1),
                   (i['decision'] == 'declined' and arow['decision'] == 'declined')]
        rules_2 = [i['shop'] == arow['shop'],
                   i['email'] == arow['email'],
                   ((i['dt'] - arow['dt']).days <=1),
                   (i['decision'] == 'accepted' and arow['decision'] == 'declined')]
        if any((rules_1,rules_2)):
            return True

def check_st(alist,aset):
    for i in alist:
        if aset.issubset(set(i)):
            print(f'There is a match')
            return True

def prune_df(sdf):
    rem_idx = []
    store = []
    idx = [0,1,2,6,10]
    for i in sdf.collect():
        if all((check_st(store,set(list(map(i.__getitem__,idx))[1:])), rules_check(i,store))):
            rem_idx.append(i['id'])
        else:
            store.append(i)
    pruned_sdf = sdf.filter(~sdf.id.isin(rem_idx))
    return pruned_sdf
</code>```

This code above returns back the dataframe without pruning the rows that fitting the category. I assume the bug is around if aset.issubset(set(i)): statement since it does not print There is a match although I am aware that there are several matches in the dataset.

Body:
I am pretty new in pyspark, so any help is appreciated. I am trying iterate through a pyspark Dataframe, and filter it out from the rows that meet certain rules.

The Dataframe looks like this:

root
 |-- id: long (nullable = true)
 |-- email: string (nullable = true)
 |-- status: string (nullable = true)
 |-- foo: string (nullable = true)
 |-- bar: decimal(36,16) (nullable = true)
 |-- foobar: decimal(36,16) (nullable = true)
 |-- decision: string (nullable = true)
 |-- spam: string (nullable = true)
 |-- foobarfoo: decimal(36,16) (nullable = true)
 |-- shop: long (nullable = true)
 |-- dt: timestamp (nullable = true)

This is what I could come up so far, but this does not accomplish the task:

def rules_check(arow,alist):
    for i in alist:
        rules_1 = [i['shop'] == arow['shop'],
                   i['email'] == arow['email'],
                   ((i['dt'] - arow['dt']).days <=1),
                   (i['decision'] == 'declined' and arow['decision'] == 'declined')]
        rules_2 = [i['shop'] == arow['shop'],
                   i['email'] == arow['email'],
                   ((i['dt'] - arow['dt']).days <=1),
                   (i['decision'] == 'accepted' and arow['decision'] == 'declined')]
        if any((rules_1,rules_2)):
            return True

def check_st(alist,aset):
    for i in alist:
        if aset.issubset(set(i)):
            print(f'There is a match')
            return True

def prune_df(sdf):
    rem_idx = []
    store = []
    idx = [0,1,2,6,10]
    for i in sdf.collect():
        if all((check_st(store,set(list(map(i.__getitem__,idx))[1:])), rules_check(i,store))):
            rem_idx.append(i['id'])
        else:
            store.append(i)
    pruned_sdf = sdf.filter(~sdf.id.isin(rem_idx))
    return pruned_sdf

This code above returns back the dataframe without pruning the rows that fitting the category. I assume the bug is around if aset.issubset(set(i)): statement since it does not print There is a match although I am aware that there are several matches in the dataset.


问:
Git : a commit that stands alone
I found a commit in my tree that stands strictly alone : no parents, no children. I stumbled upon it because I noticed it was appearing in all my log -S/-G searches. And indeed, since it stands alone, in order to describe the state of things at this commit, it contains the whole world - instead of a diff to a parent like in the normal case. So everything in my system is referenced specifically in this commit, and thus found in searches.

Also I found another commit with the exact same commit message from around the same time. The diff between the two is very small and has no meaningful content - mostly cosmetic blanks lines here and there. This commit is well integrated in the tree.

The commit that stands alone is also the one to which a remote branch points. Maybe that's why it's still advertised, despite whatever happened to it that left it to stand entirely alone.

Can I force the branch to go to the other, more meaningful commit, and thus forget about that stand-alone one ?

How could this ever happen ? Is there any good practice I could follow to prevent this from happening again ?

Title: Git : a commit that stands alone


问:
UK base Stripe recurring payment not working
I am implementing stripe recurring payment UK base (I mean 3d secure) in PHP & react-native
But I am getting the issue on the next payment.
I need to set auto-cut payment from the customer's card

Is there any way to set a subscription based on hourly?
because it will take too much time to check whether it working or not.
I am suffering  from the last 2 weeks and  still, issue could  not resolve.

$stripeSubscription = $stripe->subscriptions->create([
    'customer' =>  $stripeCustomerID,
    'items' => [
        ['price' => $stripePriceID],
    ],
    'payment_behavior' => 'default_incomplete',
    'expand' => ['latest_invoice.payment_intent'],
    'payment_settings' => ['save_default_payment_method' => 'on_subscription'],
])
$stripeClientSecret     = $stripeSubscription->latest_invoice->payment_intent->client_secret;
```
<pre class="lang-js prettyprint-override"><code>import { confirmPayment, CardForm, initStripe } from '@stripe/stripe-react-native';

useEffect(() => {
    initStripe({
        publishableKey: 'stripe key',
    });
}, []);

// on submit
const stripeClientSecret = "we getting from php side";
const confirmPaymentResult = await confirmPayment(stripeClientSecret, {
    paymentMethodType: 'Card',
    paymentMethodData: {
        billingDetails,
    },
});

// design
<CardForm
    style={{
        width: '100%',
        height: 160,
    }}
/>
</code>```

Body:
I am implementing stripe recurring payment UK base (I mean 3d secure) in PHP & react-native
But I am getting the issue on the next payment.
I need to set auto-cut payment from the customer's card

Is there any way to set a subscription based on hourly?
because it will take too much time to check whether it working or not.
I am suffering  from the last 2 weeks and  still, issue could  not resolve.

$stripeSubscription = $stripe->subscriptions->create([
    'customer' =>  $stripeCustomerID,
    'items' => [
        ['price' => $stripePriceID],
    ],
    'payment_behavior' => 'default_incomplete',
    'expand' => ['latest_invoice.payment_intent'],
    'payment_settings' => ['save_default_payment_method' => 'on_subscription'],
])
$stripeClientSecret     = $stripeSubscription->latest_invoice->payment_intent->client_secret;

import { confirmPayment, CardForm, initStripe } from '@stripe/stripe-react-native';

useEffect(() => {
    initStripe({
        publishableKey: 'stripe key',
    });
}, []);

// on submit
const stripeClientSecret = "we getting from php side";
const confirmPaymentResult = await confirmPayment(stripeClientSecret, {
    paymentMethodType: 'Card',
    paymentMethodData: {
        billingDetails,
    },
});

// design
<CardForm
    style={{
        width: '100%',
        height: 160,
    }}
/>


问:
How to exclude a particular module and it's dependencies in webpack?
I'm building a website + native app using expo managed workflow. (All three platforms)

I'm using Apache echarts for web and victory-native for native devices. I can just reference Chart.tsx and Chart.native.tsx for it to pick it up.

Webpack configured by expo does a good work in excluding the victory-native module because it's not being imported in any non native files. Now the problem comes with the dependencies of it. 'lodash' in particular is used by victory-native in its dependencies, and it is slipping through and getting included in my bundle when I checked using webpack-bundle-analyzer.

I have cross checked if I was using lodash in any of my components or if I installed it explicitly in my package.json, but no. My package.json doesn't contain lodash in any form, but when I searched for it, it was existing under dependencies of victory-native module. This is how I came to conclusion that even though victory-native or rather any module having victory-* or the victory module itself, is excluded from the bundle, it's dependency, 'lodash' in particular is getting bundled.

Is there any way I can exclude it from my bundle for web totally?

Currently I don't have any custom configuration in webpack.config.js. I'm just letting expo take care of it, but I've started reading about how to customize certain stuff so that I can have an optimized bundle to my purposes. I'm a beginner with webpack, any feedback is appreciated. Thank you.


问:
How to disable raspberry pi support in libcec when building from source on a non raspberry pi device?
I used -DHAVE_AOCEC_API=1 to enable aocec support.

I wanted to disable raspberry pi support because i don't even have a raspberry pi and it caused problems when building on a non raspberry pi system "fatal error: interface/vmcs_host/vc_cecservice.h: No such file or directory"

How do i properly disable raspberry pi support?

I tried using -DHAVE_RPI_API=0 to disable it but it still got configured with raspberry pi support. "Raspberry Pi support: yes".


问:
Why does athena:GetDataCatalog fails for the default "AwsDataCatalog"?
When I list the data catalogs from athena I get:

```<code>aws athena list-data-catalogs
{
    "DataCatalogsSummary": [
        {
            "CatalogName": "AwsDataCatalog",
            "Type": "GLUE"
        }
    ]
}
</code>```

So there is data catalog named AwsDataCatalog which I learned is the default AWS Glue Data Catalog.

I can use AwsDataCatalog in

```<code>aws athena list-databases --catalog-name AwsDataCatalog

</code>```

If I try to perform GetDataCatalog on it I get DataCatalog AwsDataCatalog was not found`

```<code>aws --version
aws-cli/2.9.12 Python/3.11.1 Darwin/21.6.0 source/x86_64 prompt/off

aws athena get-data-catalog --name AwsDataCatalog

An error occurred (InvalidRequestException) when calling the GetDataCatalog operation: DataCatalog AwsDataCatalog was not found.
</code>```

Is this the expected behaviour or I'm doing something wrong?

I would expected that it would give something like

```<code>{
    "DataCatalog": {
        "Name": "AwsDataCatalog",
        "Description": "Default Data Catalog",
        "Type": "GLUE",
        "Parameters": {
            "catalog_id": "<my-aws-account-id>",

        }
    }
}
</code>```

In any case I just want to know if that is the expected behavior (as in it's the same for everybody else). As I know the response for AwsDataCatalog is always going to be GLUE so there is no point on actually doing GetDataCatalog on it.

Body:
When I list the data catalogs from athena I get:

aws athena list-data-catalogs
{
    "DataCatalogsSummary": [
        {
            "CatalogName": "AwsDataCatalog",
            "Type": "GLUE"
        }
    ]
}

So there is data catalog named AwsDataCatalog which I learned is the default AWS Glue Data Catalog.

I can use AwsDataCatalog in

aws athena list-databases --catalog-name AwsDataCatalog

If I try to perform GetDataCatalog on it I get DataCatalog AwsDataCatalog was not found`

aws --version
aws-cli/2.9.12 Python/3.11.1 Darwin/21.6.0 source/x86_64 prompt/off

aws athena get-data-catalog --name AwsDataCatalog

An error occurred (InvalidRequestException) when calling the GetDataCatalog operation: DataCatalog AwsDataCatalog was not found.

Is this the expected behaviour or I'm doing something wrong?

I would expected that it would give something like

{
    "DataCatalog": {
        "Name": "AwsDataCatalog",
        "Description": "Default Data Catalog",
        "Type": "GLUE",
        "Parameters": {
            "catalog_id": "<my-aws-account-id>",

        }
    }
}

In any case I just want to know if that is the expected behavior (as in it's the same for everybody else). As I know the response for AwsDataCatalog is always going to be GLUE so there is no point on actually doing GetDataCatalog on it.


问:
How to get the changes in azure active directory to be notified by the nest application?
I have followed this link https://learn.microsoft.com/en-us/graph/change-notifications-delivery#configuring-the-azure-event-hub to get the changes in AD.
when I trigger an API only I am getting the notifications in application side but it should be like, my application should get the events when any user is added or updated automatically from eventhub. How can I do that.
please help me to proceed further

subscription request, notification url is given as mentioned in the link :  https://learn.microsoft.com/en-us/graph/change-notifications-delivery#configuring-the-azure-event-hub

const subscription = {
resource: "users",
notificationUrl: "**********************",
changeType: "created,updated",
expirationDateTime: activationDate,
clientState: "secretClientValue",
latestSupportedTlsVersion: " v1_2"
};

```<code>try {
   const res = await client.api('/subscriptions').post(subscription);
   console.log("response from subscription request", res);
</code>```

}

how to listen the events from eventhub by the application automatically

Body:
I have followed this link https://learn.microsoft.com/en-us/graph/change-notifications-delivery#configuring-the-azure-event-hub to get the changes in AD.
when I trigger an API only I am getting the notifications in application side but it should be like, my application should get the events when any user is added or updated automatically from eventhub. How can I do that.
please help me to proceed further

subscription request, notification url is given as mentioned in the link :  https://learn.microsoft.com/en-us/graph/change-notifications-delivery#configuring-the-azure-event-hub

const subscription = {
resource: "users",
notificationUrl: "**********************",
changeType: "created,updated",
expirationDateTime: activationDate,
clientState: "secretClientValue",
latestSupportedTlsVersion: " v1_2"
};

try {
   const res = await client.api('/subscriptions').post(subscription);
   console.log("response from subscription request", res);

}

how to listen the events from eventhub by the application automatically


问:
Unable to access parameters from configuration.yaml using dependency-injector
I am unable to load the parameters I have in a configuration.yaml.

containers.py

```<code>class Container(containers.DeclarativeContainer):
    config = providers.Configuration(yaml_files=None)

    match_worker = providers.Singleton(Admin,
                                       key=config.key)

def initialize(config_path: Optional[str] = None) -> Container:
    container = Container()
    if config_path:
        container.config.from_yaml(config_path, required=True)

    return container
</code>```

notebook.py

```<code>from myNotebook.containers import initialize

container = initialize('../../configuration.yaml')
container.config()
</code>```

admin.py

```<code>from dependency_injector.wiring import inject, Provide

class Admin
    @inject
    def __init__(
            self,
            key: str,
            config: dict = Provide["config"]
    ):
        self._key: str = key
        self._config = config

    def _retrieve(self) -> str:
        a = self._config()
        print(a)
        print(a.stage())
</code>```

And the first print statement gives:

```<code><dependency_injector.wiring.Provide object at 0x7f62d62574f0>
</code>```

However, for the second print statement I get an AttributeErrror:

```<code>'Provide' object has no attribute 'stage'
</code>```

I've tried several permutations to access the parameters however to no avail. I'm very new to dependency-injector, I suspect it is something else in the code that is incorrect. How can I resolve this issue?

Body:
I am unable to load the parameters I have in a configuration.yaml.

containers.py

class Container(containers.DeclarativeContainer):
    config = providers.Configuration(yaml_files=None)

    match_worker = providers.Singleton(Admin,
                                       key=config.key)

def initialize(config_path: Optional[str] = None) -> Container:
    container = Container()
    if config_path:
        container.config.from_yaml(config_path, required=True)

    return container

notebook.py

from myNotebook.containers import initialize

container = initialize('../../configuration.yaml')
container.config()

admin.py

from dependency_injector.wiring import inject, Provide

class Admin
    @inject
    def __init__(
            self,
            key: str,
            config: dict = Provide["config"]
    ):
        self._key: str = key
        self._config = config

    def _retrieve(self) -> str:
        a = self._config()
        print(a)
        print(a.stage())

And the first print statement gives:

<dependency_injector.wiring.Provide object at 0x7f62d62574f0>

However, for the second print statement I get an AttributeErrror:

'Provide' object has no attribute 'stage'

I've tried several permutations to access the parameters however to no avail. I'm very new to dependency-injector, I suspect it is something else in the code that is incorrect. How can I resolve this issue?


问:
ClickHouse - How can I control Replica Insert behavior
I have a Cluster with 2 Shard, each Shard has 2-3 Replicas.

I created a ReplicatedMergeTree in each replica and insert data to them through a Distributed table with rand() sharding key.

I have internal_replication = true, after inserted 1.1M record so this is the result I got:

Shard 1 - Rep 1: 530K records

Shard 1 - Rep 2: 20K records

Shard 1 - Rep 3: 0 records

Shard 2 - Rep 1: 550K records (I run insert command on this node)

Shard 2 - Rep 2: 0 records

I ran count() query on Distributed table and got 1.08M (expected 1.1M)
seem ClickHouse only get data from one Replica of each Shard.

How can I make it get data from all Replica in each Shard and insert balance into each Replica (expectd ~200K records per Replica in Shard 1)


问:
How to redirect to the Auth0 login page automatically, when the application URL is typed in the browser
To configure the application login URI in Auth0 for Single Page Application in angular. To redirect to the Auth0 login page automatically, when the application URL is typed in the browser. Instead of triggering the Login page from browser via button or some other action.

When I'm trying I'm getting angular application login page and then auth0 login page is coming. But I want only auth0 login page.


问:
Issue in Kafka Spring boot test cases for AdminClient
I am writing unit test cases for below class . I'm trying to mock admin client , so that i can call the below method create topic. But getting null pointer exception.

```<code>@Service
public class TopicService {

  private static final Logger LOG = LoggerFactory.getLogger(TopicService.class);
@Autowired
  private AdminClient adminClient;

public void createTopic(Topic topic) throws ExecutionException, InterruptedException {
    adminClient
            .createTopics(Collections.singletonList(ServiceHelper.fromTopic(topic)))
            .values()
            .get(topic.getName())
            .get();
  }
}
</code>```

The unit test case is as follows

```<code>package org.kafka.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.ListTopicsResult;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.KafkaFuture;
import org.apache.kafka.common.internals.KafkaFutureImpl;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kafka.model.Topic;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;
import java.util.concurrent.ExecutionException;

import static org.apache.kafka.clients.admin.AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.apache.kafka.clients.admin.AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG;
import static org.apache.kafka.common.internals.Topic.GROUP_METADATA_TOPIC_NAME;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TopicService.class})
public class TopicServiceTest {

    @Autowired
    TopicService topicService;

    @MockBean
    AdminClient adminClient;
    ListTopicsResult listTopicsResult;

    KafkaFuture<Set<String>> future;

    NewTopic newTopic;

    Topic topic;

    Collection<NewTopic> topicList;

    CreateTopicsResult createTopicsResult;
    Void t;

    Map<String,KafkaFuture<Void>> futureMap;

    private static final String TARGET_CONSUMER_GROUP_ID = "target-group-id";

    private static final Map<String, Object> CONF = new HashMap<>();

    @BeforeClass
    public static void createAdminClient() {
        try {
            CONF.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
            CONF.put(REQUEST_TIMEOUT_MS_CONFIG, 120000);
            CONF.put("zookeeper.connect", "localhost:21891");

           AdminClient adminClient = AdminClient.create(CONF);
        } catch (Exception e) {
            throw new RuntimeException("create kafka admin client error", e);
        }
    }

    @Before
    public void setUp(){
        topicList = new ArrayList<>();
        newTopic = new NewTopic("topic-7",1, (short) 1);
        topicList.add(newTopic);
        futureMap = new HashMap<>();
        topic = new Topic();
        topic.setName("topic-1");
    }

    @Test
    public void createTopic() throws ExecutionException, InterruptedException {

        Properties consumerProperties = new Properties();

        Mockito.when(adminClient.createTopics(topicList))
                .thenReturn(Mockito.mock(CreateTopicsResult.class));

        Mockito.when(adminClient.createTopics(topicList).values())
                .thenReturn(Mockito.mock(Map.class));

        Mockito.when(adminClient.createTopics(topicList)
                .values()
                .get(GROUP_METADATA_TOPIC_NAME)).thenReturn(Mockito.mock(KafkaFutureImpl.class));

        Mockito.when(adminClient.createTopics(topicList)
                .values()
                .get(GROUP_METADATA_TOPIC_NAME)
                .get()).thenReturn(t);
         topicService.createTopic(topic);
    }
}

</code>```
```<code>package org.kafka.config;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.kafka.reader.Kafka;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AdminConfigurer {

    @Autowired
    private Kafka kafkaConfig;

    @Bean
    public Map<String, Object> kafkaAdminProperties() {
        final Map<String, Object> configs = new HashMap<>();
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfig.getBootstrapServers());
        if(kafkaConfig.getProperties().getSasl().getEnabled() && kafkaConfig.getSsl().getEnabled()) {
            configs.put("sasl.mechanism", kafkaConfig.getProperties().getSasl().getMechanism());
            configs.put("security.protocol", kafkaConfig.getProperties().getSasl().getSecurity().getProtocol());
            configs.put("ssl.keystore.location", kafkaConfig.getSsl().getKeystoreLocation());
            configs.put("ssl.keystore.password", kafkaConfig.getSsl().getKeystorePassword());
            configs.put("ssl.truststore.location", kafkaConfig.getSsl().getTruststoreLocation());
            configs.put("ssl.truststore.password", kafkaConfig.getSsl().getTruststorePassword());
            configs.put("sasl.jaas.config", String.format(kafkaConfig.getJaasTemplate(),
                    kafkaConfig.getProperties().getSasl().getJaas().getConfig().getUsername(),
                    kafkaConfig.getProperties().getSasl().getJaas().getConfig().getPassword()));
            configs.put("ssl.endpoint.identification.algorithm", "");
        }
        return configs;
    }

    @Bean
    public AdminClient getClient() {
        return AdminClient.create(kafkaAdminProperties());
    }

}
</code>```

I expected the below test case run successfully. But i'm getting below error.

```<code>java.lang.NullPointerException
    at org.kafka.service.TopicService.createTopic(TopicService.java:57)
    at org.kafka.service.TopicServiceTest.createTopic(TopicServiceTest.java:100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
</code>```

I'm using 2.7.1 spring version with following client dependency.

```<code>                <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>3.1.1</version>
            <scope>test</scope>
            <classifier>test</classifier>
        </dependency>

                 <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
</code>```

Body:
I am writing unit test cases for below class . I'm trying to mock admin client , so that i can call the below method create topic. But getting null pointer exception.

@Service
public class TopicService {

  private static final Logger LOG = LoggerFactory.getLogger(TopicService.class);
@Autowired
  private AdminClient adminClient;

public void createTopic(Topic topic) throws ExecutionException, InterruptedException {
    adminClient
            .createTopics(Collections.singletonList(ServiceHelper.fromTopic(topic)))
            .values()
            .get(topic.getName())
            .get();
  }
}

The unit test case is as follows

package org.kafka.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.ListTopicsResult;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.KafkaFuture;
import org.apache.kafka.common.internals.KafkaFutureImpl;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kafka.model.Topic;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;
import java.util.concurrent.ExecutionException;

import static org.apache.kafka.clients.admin.AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.apache.kafka.clients.admin.AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG;
import static org.apache.kafka.common.internals.Topic.GROUP_METADATA_TOPIC_NAME;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TopicService.class})
public class TopicServiceTest {

    @Autowired
    TopicService topicService;

    @MockBean
    AdminClient adminClient;
    ListTopicsResult listTopicsResult;

    KafkaFuture<Set<String>> future;

    NewTopic newTopic;

    Topic topic;

    Collection<NewTopic> topicList;

    CreateTopicsResult createTopicsResult;
    Void t;

    Map<String,KafkaFuture<Void>> futureMap;

    private static final String TARGET_CONSUMER_GROUP_ID = "target-group-id";

    private static final Map<String, Object> CONF = new HashMap<>();

    @BeforeClass
    public static void createAdminClient() {
        try {
            CONF.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
            CONF.put(REQUEST_TIMEOUT_MS_CONFIG, 120000);
            CONF.put("zookeeper.connect", "localhost:21891");

           AdminClient adminClient = AdminClient.create(CONF);
        } catch (Exception e) {
            throw new RuntimeException("create kafka admin client error", e);
        }
    }

    @Before
    public void setUp(){
        topicList = new ArrayList<>();
        newTopic = new NewTopic("topic-7",1, (short) 1);
        topicList.add(newTopic);
        futureMap = new HashMap<>();
        topic = new Topic();
        topic.setName("topic-1");
    }

    @Test
    public void createTopic() throws ExecutionException, InterruptedException {

        Properties consumerProperties = new Properties();

        Mockito.when(adminClient.createTopics(topicList))
                .thenReturn(Mockito.mock(CreateTopicsResult.class));

        Mockito.when(adminClient.createTopics(topicList).values())
                .thenReturn(Mockito.mock(Map.class));

        Mockito.when(adminClient.createTopics(topicList)
                .values()
                .get(GROUP_METADATA_TOPIC_NAME)).thenReturn(Mockito.mock(KafkaFutureImpl.class));

        Mockito.when(adminClient.createTopics(topicList)
                .values()
                .get(GROUP_METADATA_TOPIC_NAME)
                .get()).thenReturn(t);
         topicService.createTopic(topic);
    }
}

package org.kafka.config;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.kafka.reader.Kafka;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AdminConfigurer {

    @Autowired
    private Kafka kafkaConfig;

    @Bean
    public Map<String, Object> kafkaAdminProperties() {
        final Map<String, Object> configs = new HashMap<>();
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfig.getBootstrapServers());
        if(kafkaConfig.getProperties().getSasl().getEnabled() && kafkaConfig.getSsl().getEnabled()) {
            configs.put("sasl.mechanism", kafkaConfig.getProperties().getSasl().getMechanism());
            configs.put("security.protocol", kafkaConfig.getProperties().getSasl().getSecurity().getProtocol());
            configs.put("ssl.keystore.location", kafkaConfig.getSsl().getKeystoreLocation());
            configs.put("ssl.keystore.password", kafkaConfig.getSsl().getKeystorePassword());
            configs.put("ssl.truststore.location", kafkaConfig.getSsl().getTruststoreLocation());
            configs.put("ssl.truststore.password", kafkaConfig.getSsl().getTruststorePassword());
            configs.put("sasl.jaas.config", String.format(kafkaConfig.getJaasTemplate(),
                    kafkaConfig.getProperties().getSasl().getJaas().getConfig().getUsername(),
                    kafkaConfig.getProperties().getSasl().getJaas().getConfig().getPassword()));
            configs.put("ssl.endpoint.identification.algorithm", "");
        }
        return configs;
    }

    @Bean
    public AdminClient getClient() {
        return AdminClient.create(kafkaAdminProperties());
    }

}

I expected the below test case run successfully. But i'm getting below error.

java.lang.NullPointerException
    at org.kafka.service.TopicService.createTopic(TopicService.java:57)
    at org.kafka.service.TopicServiceTest.createTopic(TopicServiceTest.java:100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

I'm using 2.7.1 spring version with following client dependency.

                <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>3.1.1</version>
            <scope>test</scope>
            <classifier>test</classifier>
        </dependency>

                 <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>


问:
route to a specific component in angular from email
Working on an Angular app where I need to route to a specific URL which will be receiving in the email. But to access that particular route, user must be logged-in.

So, at first, when user click that URL in their email he/she will land onto the login screen to login (because login is required to access the application) which is fine. Now, my question is how I can route the user to that specific route which was received in the email just after successful login?

Any suggestion will be really appreciated!!


问:
Roberta on local CPU tensor mismatch at non-singleton dimension 1
I downloaded https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment model to my local pc.
When I pull the model from the website it works perfectly fine but it gave me tensor mismatch error on local.

```<code>`self.MODEL = "C:/Users/metehan/project1/MLTools/twitter-roberta-base-sentiment"
self.model = AutoModelForSequenceClassification.from_pretrained(self.MODEL)
self.tokenizer = AutoTokenizer.from_pretrained(self.MODEL)
self.labels = ['Negative', 'Neutral', 'Positive']`
</code>```

Vocabulary sizes of model and tokenizer are the same and I don't use GPU so model, tokenizer and inputs are at the same location.

```<code>`encoded_tweet = self.tokenizer(eng_tweet, return_tensors='pt')
output = self.model(**encoded_tweet)
scores = output[0][0].detach().numpy()
scores = softmax(scores)
max_value = max(scores)`

(base) C:\Users\metehan\project1>python test.py
Traceback (most recent call last):
  File "C:\Users\metehan\project1\MLTools\analyze_tweets.py", line 34, in analyze
    output = self.model(**encoded_tweet)
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\torch\nn\modules\module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\transformers\models\roberta\modeling_roberta.py", line 1206, in forward
    outputs = self.roberta(
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\torch\nn\modules\module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\transformers\models\roberta\modeling_roberta.py", line 814, in forward
    buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
RuntimeError: The expanded size of the tensor (685) must match the existing size (514) at non-singleton dimension 1.  Target sizes: [1, 685].  Tensor sizes: [1, 514]
</code>```

I tried adding padding and truncation to tokenizer but an index error has occured. Also adding tokenizer a max length didn't work.
Any idea how to fix this?

Body:
I downloaded https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment model to my local pc.
When I pull the model from the website it works perfectly fine but it gave me tensor mismatch error on local.

`self.MODEL = "C:/Users/metehan/project1/MLTools/twitter-roberta-base-sentiment"
self.model = AutoModelForSequenceClassification.from_pretrained(self.MODEL)
self.tokenizer = AutoTokenizer.from_pretrained(self.MODEL)
self.labels = ['Negative', 'Neutral', 'Positive']`

Vocabulary sizes of model and tokenizer are the same and I don't use GPU so model, tokenizer and inputs are at the same location.

`encoded_tweet = self.tokenizer(eng_tweet, return_tensors='pt')
output = self.model(**encoded_tweet)
scores = output[0][0].detach().numpy()
scores = softmax(scores)
max_value = max(scores)`

(base) C:\Users\metehan\project1>python test.py
Traceback (most recent call last):
  File "C:\Users\metehan\project1\MLTools\analyze_tweets.py", line 34, in analyze
    output = self.model(**encoded_tweet)
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\torch\nn\modules\module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\transformers\models\roberta\modeling_roberta.py", line 1206, in forward
    outputs = self.roberta(
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\torch\nn\modules\module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\metehan\AppData\Roaming\Python\Python39\site-packages\transformers\models\roberta\modeling_roberta.py", line 814, in forward
    buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
RuntimeError: The expanded size of the tensor (685) must match the existing size (514) at non-singleton dimension 1.  Target sizes: [1, 685].  Tensor sizes: [1, 514]

I tried adding padding and truncation to tokenizer but an index error has occured. Also adding tokenizer a max length didn't work.
Any idea how to fix this?


问:
SpringData JPA saveAll() followed by flush() not reflecting immediately in other docker containers
I have a Spring based web service hosted as Docker Containers with multiple instances running.
There are two end-point causing the issue result 25 precent of the time.
The following are the end points :

API-1 @PostMapping("v1/calculate")
Calculates the progress of a certian user and persists it in the database using saveAll() followed by flush().

API-2 @GetMapping("v1/fetch")
Gets the progress data of the user using native query.

Solutions Tried :

API-1 I have replaced the save method to saveAll followed by flush() for quicker persistence.

API-2 I have avoided using getById method to by pass the Hibernate Level -1 caching.

When data is persisted using API-1 and then API-2 is consequnetly called.
25% of the time API-2 returns users not found.

```<code>Tech Stack of the Project :
Spring-Boot 3.0.0
Spring Data JPA 3.0.0
hibernate-core 6.1.5 Final
PostgreSQL 12.11
</code>```
```<code>application.properties :
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.batch_size = 20
spring.jpa.properties.hibernate.order_updates = true
spring.jpa.properties.hibernate.order_inserts = true
</code>```

Expecting for the Entity to be reflected in remaining containers immediately.

Body:
I have a Spring based web service hosted as Docker Containers with multiple instances running.
There are two end-point causing the issue result 25 precent of the time.
The following are the end points :

API-1 @PostMapping("v1/calculate")
Calculates the progress of a certian user and persists it in the database using saveAll() followed by flush().

API-2 @GetMapping("v1/fetch")
Gets the progress data of the user using native query.

Solutions Tried :

API-1 I have replaced the save method to saveAll followed by flush() for quicker persistence.

API-2 I have avoided using getById method to by pass the Hibernate Level -1 caching.

When data is persisted using API-1 and then API-2 is consequnetly called.
25% of the time API-2 returns users not found.

Tech Stack of the Project :
Spring-Boot 3.0.0
Spring Data JPA 3.0.0
hibernate-core 6.1.5 Final
PostgreSQL 12.11

application.properties :
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.batch_size = 20
spring.jpa.properties.hibernate.order_updates = true
spring.jpa.properties.hibernate.order_inserts = true

Expecting for the Entity to be reflected in remaining containers immediately.


问:
Match values from one data frame based on a second in R
I have two data frames.

One contains a number of participants that have a score each. For instance:

```<code>participant score
Sally       2
Bill        2
Maria       5
Sophie      1
Jack        2
</code>```

Now I have a second dataframe which tells me additional number to match with each score. Its first column contains every score possible. For instance:

```<code>Score number 1 number 2
1     365.85   738.94
2     64985.8  746.9
3     36.98    254.0
4     738.9    738.98
5     73.96    77.9
</code>```

In reality the data is much larger.
Now I want to match them. So each participant should get number 1 and number 2 BASED ON their score.

Can anybody help? Thank you!

Body:
I have two data frames.

One contains a number of participants that have a score each. For instance:

participant score
Sally       2
Bill        2
Maria       5
Sophie      1
Jack        2

Now I have a second dataframe which tells me additional number to match with each score. Its first column contains every score possible. For instance:

Score number 1 number 2
1     365.85   738.94
2     64985.8  746.9
3     36.98    254.0
4     738.9    738.98
5     73.96    77.9

In reality the data is much larger.
Now I want to match them. So each participant should get number 1 and number 2 BASED ON their score.

Can anybody help? Thank you!


问:
Elasticsearch – Group by field name and count number of last event occurrences from each group
I am trying to get count of running and stopped processes based on indexed log messages.
In a relational database, I would have table and SQL query like this:

logs_tbl

```<code>| process_name  | process_status | timestamp        |
| ------------- | -------------- | ---------------- |
| p01           | Running        | 12/7/22 2:35 PM  |
| p02           | Running        | 12/7/22 2:35 PM  |
| p03           | Running        | 12/7/22 2:36 PM  |
| p04           | Running        | 12/7/22 2:36 PM  |
| p02           | Stopped        | 12/7/22 2:37 PM  |
| p04           |                | 12/7/22 2:39 PM  |
| p03           | Stopped        | 12/7/22 11:22 PM |
| p03           | Running        | 12/7/22 11:23 PM |
| p01           | Stopped        | 12/8/22 2:37 PM  |
</code>```
```<code>SELECT logs_tbl.process_status, Count(logs_tbl.process_status) AS CountOfprocess_status
FROM logs_tbl
INNER JOIN (SELECT logs_tbl.process_name, MAX(logs_tbl.timestamp) AS last_time
FROM logs_tbl
WHERE logs_tbl.process_status Is Not Null GROUP BY logs_tbl.process_name)  AS t2
ON (logs_tbl.timestamp = t2.last_time) AND (logs_tbl.process_name = t2.process_name)
GROUP BY logs_tbl.process_status;
</code>```

As a result, I will get:

```<code>Running 2
Stopped 2
</code>```

In Elasticsearch, I have the following index mapping.

```<code>{
  "process_logs" : {
    "mappings" : {
      "properties" : {
        "@timestamp" : {
          "type" : "date"
        },
        "@version" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "process_attributes" : {
          "properties" : {
            "process_id" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "process_name" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            }
          }
        },
        "process_status" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}
</code>```

And I tried the following DSL query:

```<code>GET /process_logs*/_search
{
  "size": 0,
  "query": {
    "exists": {
      "field": "process_status"
    }
  },
  "aggs": {
    "processes": {
      "terms": {
        "field": "process_attributes.process_name.keyword"
      },
      "aggs": {
        "last_status": {
          "max": {
            "field": "@timestamp"
          }
        }
      }
    }
  }
}
</code>```

As a result, I got:

```<code>  "aggregations" : {
    "processes" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "p1",
          "doc_count" : 2,
          "last_status" : {
            "value" : 1.66686408E12,
            "value_as_string" : "2022-10-27T09:48:00.000Z"
          }
        },
        {
          "key" : "p2",
          "doc_count" : 1,
          "last_status" : {
            "value" : 1.666864149E12,
            "value_as_string" : "2022-10-27T09:49:09.000Z"
          }
        }
      ]
    }
  }
</code>```

At this moment I have the time of last status of each process, and I need to count different process_status types.

Any idea please.

Body:
I am trying to get count of running and stopped processes based on indexed log messages.
In a relational database, I would have table and SQL query like this:

logs_tbl

| process_name  | process_status | timestamp        |
| ------------- | -------------- | ---------------- |
| p01           | Running        | 12/7/22 2:35 PM  |
| p02           | Running        | 12/7/22 2:35 PM  |
| p03           | Running        | 12/7/22 2:36 PM  |
| p04           | Running        | 12/7/22 2:36 PM  |
| p02           | Stopped        | 12/7/22 2:37 PM  |
| p04           |                | 12/7/22 2:39 PM  |
| p03           | Stopped        | 12/7/22 11:22 PM |
| p03           | Running        | 12/7/22 11:23 PM |
| p01           | Stopped        | 12/8/22 2:37 PM  |

SELECT logs_tbl.process_status, Count(logs_tbl.process_status) AS CountOfprocess_status
FROM logs_tbl
INNER JOIN (SELECT logs_tbl.process_name, MAX(logs_tbl.timestamp) AS last_time
FROM logs_tbl
WHERE logs_tbl.process_status Is Not Null GROUP BY logs_tbl.process_name)  AS t2
ON (logs_tbl.timestamp = t2.last_time) AND (logs_tbl.process_name = t2.process_name)
GROUP BY logs_tbl.process_status;

As a result, I will get:

Running 2
Stopped 2

In Elasticsearch, I have the following index mapping.

{
  "process_logs" : {
    "mappings" : {
      "properties" : {
        "@timestamp" : {
          "type" : "date"
        },
        "@version" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "process_attributes" : {
          "properties" : {
            "process_id" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "process_name" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            }
          }
        },
        "process_status" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

And I tried the following DSL query:

GET /process_logs*/_search
{
  "size": 0,
  "query": {
    "exists": {
      "field": "process_status"
    }
  },
  "aggs": {
    "processes": {
      "terms": {
        "field": "process_attributes.process_name.keyword"
      },
      "aggs": {
        "last_status": {
          "max": {
            "field": "@timestamp"
          }
        }
      }
    }
  }
}

As a result, I got:

  "aggregations" : {
    "processes" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "p1",
          "doc_count" : 2,
          "last_status" : {
            "value" : 1.66686408E12,
            "value_as_string" : "2022-10-27T09:48:00.000Z"
          }
        },
        {
          "key" : "p2",
          "doc_count" : 1,
          "last_status" : {
            "value" : 1.666864149E12,
            "value_as_string" : "2022-10-27T09:49:09.000Z"
          }
        }
      ]
    }
  }

At this moment I have the time of last status of each process, and I need to count different process_status types.

Any idea please.


问:
Problems in "Add to Cart" using react redux-toolkit and localstorage
I am adding "add to cart" feature to the eCommerce site using redux-toolkit. I am also using local storage and thunk but it is not working. Products are not added to the cart. Nothing shows on the console. What is wrong with this code?

Here is the CartSlice.js code

```<code>import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const cartItemsFromStorage = localStorage.getItem("cartItems")
  ? JSON.parse(localStorage.getItem("cartItems"))
  : [];

const initialState = {
  cartItems: cartItemsFromStorage,
};

export const cartSlice = createSlice({
  name: "cartPage",
  initialState,
  reducers: {
    addItem(state, action) {
      const item = action.payload;
      const existItem = state.cartItems.find((x) => x.product === item.product);
      if (existItem) {
        return {
          ...state,
          cartItems: state.cartItems.map((x) =>
            x.product === existItem.product ? item : x
          ),
        };
      } else {
        return {
          ...state,
          cartItems: [...state.cartItems, item],
        };
      }
    },
  },
});

export const { addItem } = cartSlice.actions;
export default cartSlice.reducer;

export function addToCart(id, qty) {
  return async function addToCartThunk(dispatch, getState) {
    try {
      const { data } = await axios.get(`/api/products/${id}`);

      dispatch(
        addItem({
          product: data._id,
          name: data.name,
          image: data.image,
          price: data.price,
          countInStock: data.countInStock,
          qty,
        })
      );
      localStorage.setItem("cartItems", JSON.stringify(getState.cart));
    } catch (error) {
      console.log(error);
    }
  };
}
</code>```

Here is the Store.js code

```<code>import { configureStore } from "@reduxjs/toolkit";
import productReducer from "./productSlice";
import productDetailReducer from "./productDetailSlice";
import cartReducer from "./cartSlice";

const store = configureStore({
  reducer: {
    productList: productReducer,
    productDetails: productDetailReducer,
    cartPage: cartReducer,
  },
});

export default store;
</code>```

Here is the CartScreen.js code

```<code>import React from "react";
import { Link } from "react-router-dom";
import { useEffect } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { addToCart } from "../store/cartSlice";

const EMPTY_CART = { cartItems: [] };

const CartScreen = () => {
  const { productId } = useParams();

  const location = useLocation();
  const qty = location.search ? Number(location.search.split("=")[1]) : 1;
  const dispatch = useDispatch();

  const cart = useSelector((state) => state.cart || EMPTY_CART);
  const { cartItems } = cart;
  console.log(cartItems);

  useEffect(() => {
    if (productId) {
      dispatch(addToCart(productId, qty));
    }
  }, [dispatch, productId, qty]);

  return <div>Cart Page</div>;
};

export default CartScreen;
</code>```

Body:
I am adding "add to cart" feature to the eCommerce site using redux-toolkit. I am also using local storage and thunk but it is not working. Products are not added to the cart. Nothing shows on the console. What is wrong with this code?

Here is the CartSlice.js code

import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const cartItemsFromStorage = localStorage.getItem("cartItems")
  ? JSON.parse(localStorage.getItem("cartItems"))
  : [];

const initialState = {
  cartItems: cartItemsFromStorage,
};

export const cartSlice = createSlice({
  name: "cartPage",
  initialState,
  reducers: {
    addItem(state, action) {
      const item = action.payload;
      const existItem = state.cartItems.find((x) => x.product === item.product);
      if (existItem) {
        return {
          ...state,
          cartItems: state.cartItems.map((x) =>
            x.product === existItem.product ? item : x
          ),
        };
      } else {
        return {
          ...state,
          cartItems: [...state.cartItems, item],
        };
      }
    },
  },
});

export const { addItem } = cartSlice.actions;
export default cartSlice.reducer;

export function addToCart(id, qty) {
  return async function addToCartThunk(dispatch, getState) {
    try {
      const { data } = await axios.get(`/api/products/${id}`);

      dispatch(
        addItem({
          product: data._id,
          name: data.name,
          image: data.image,
          price: data.price,
          countInStock: data.countInStock,
          qty,
        })
      );
      localStorage.setItem("cartItems", JSON.stringify(getState.cart));
    } catch (error) {
      console.log(error);
    }
  };
}

Here is the Store.js code

import { configureStore } from "@reduxjs/toolkit";
import productReducer from "./productSlice";
import productDetailReducer from "./productDetailSlice";
import cartReducer from "./cartSlice";

const store = configureStore({
  reducer: {
    productList: productReducer,
    productDetails: productDetailReducer,
    cartPage: cartReducer,
  },
});

export default store;

Here is the CartScreen.js code

import React from "react";
import { Link } from "react-router-dom";
import { useEffect } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { addToCart } from "../store/cartSlice";

const EMPTY_CART = { cartItems: [] };

const CartScreen = () => {
  const { productId } = useParams();

  const location = useLocation();
  const qty = location.search ? Number(location.search.split("=")[1]) : 1;
  const dispatch = useDispatch();

  const cart = useSelector((state) => state.cart || EMPTY_CART);
  const { cartItems } = cart;
  console.log(cartItems);

  useEffect(() => {
    if (productId) {
      dispatch(addToCart(productId, qty));
    }
  }, [dispatch, productId, qty]);

  return
Cart Page
;
};

export default CartScreen;


问:
RuntimeError: Expected floating point type for target with class probabilities, got Long
When I run this code:

```<code>torch.nn.CrossEntropyLoss(torch.amax(predictions, 1), batch_acceptance)
</code>```

With
print(tensor([1, 1])), return "torch.amax(predictions, 1)"

and

print(tensor([0.5105, 0.5130], grad_fn=<AmaxBackward0>))
returns "tensor([1, 1])"

I get this error:

RuntimeError: Expected floating point type for target with class
probabilities, got Long

So, I tried

```<code>torch.nn.CrossEntropyLoss(torch.amax(predictions, 1)?float(), batch_acceptance)
</code>```

But I get the exact same error:

```<code>RuntimeError: Expected floating point type for target with class probabilities, got Long
</code>```

Any idea ?

Thanks

Body:
When I run this code:

torch.nn.CrossEntropyLoss(torch.amax(predictions, 1), batch_acceptance)

With
print(tensor([1, 1])), return "torch.amax(predictions, 1)"

and

print(tensor([0.5105, 0.5130], grad_fn=<AmaxBackward0>))
returns "tensor([1, 1])"

I get this error:

RuntimeError: Expected floating point type for target with class
probabilities, got Long

So, I tried

torch.nn.CrossEntropyLoss(torch.amax(predictions, 1)?float(), batch_acceptance)

But I get the exact same error:

RuntimeError: Expected floating point type for target with class probabilities, got Long

Any idea ?

Thanks


问:
Criteria API cannot get result as list
So lets assume i have User entity which has related entity TimeOffs and also the user entity has a field which is lead. I want to create Criteria Query

that takes all TimeOffs of User with fullName "George" and also all TimeOffs of users which lead is "George"!

My code:

```<code>CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<TimeOff> criteriaQuery = builder.createQuery(TimeOff.class);
        Root<TimeOff> root = criteriaQuery.from(TimeOff.class);
        Join<TimeOff, User> join = root.join("user");
        Predicate userNamePredicate = builder.equal(join.get("fullName"), "George");
        Join<TimeOff, User> leadJoin = root.join("user").join("lead");
        Predicate leadNamePredicate = builder.equal(leadJoin.get("fullName"), "George");
        criteriaQuery.select(root).where(userNamePredicate, leadNamePredicate);
        TypedQuery<TimeOff> query = entityManager.createQuery(criteriaQuery);
        List<TimeOff> timeOffs = query.getResultList();
</code>```

this is returning me an empty list .

also i have tried with this but its not getting any results :

```<code> cq.where(cb.and(userJoin.get("fullName").in("George", cb.equal(userJoin.get("lead").get("fullName"), "George"))));
</code>```

Title: Criteria API cannot get result as list

Body:
So lets assume i have User entity which has related entity TimeOffs and also the user entity has a field which is lead. I want to create Criteria Query

that takes all TimeOffs of User with fullName "George" and also all TimeOffs of users which lead is "George"!

My code:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<TimeOff> criteriaQuery = builder.createQuery(TimeOff.class);
        Root<TimeOff> root = criteriaQuery.from(TimeOff.class);
        Join<TimeOff, User> join = root.join("user");
        Predicate userNamePredicate = builder.equal(join.get("fullName"), "George");
        Join<TimeOff, User> leadJoin = root.join("user").join("lead");
        Predicate leadNamePredicate = builder.equal(leadJoin.get("fullName"), "George");
        criteriaQuery.select(root).where(userNamePredicate, leadNamePredicate);
        TypedQuery<TimeOff> query = entityManager.createQuery(criteriaQuery);
        List<TimeOff> timeOffs = query.getResultList();

this is returning me an empty list .

also i have tried with this but its not getting any results :

 cq.where(cb.and(userJoin.get("fullName").in("George", cb.equal(userJoin.get("lead").get("fullName"), "George"))));


问:
Angular : Override console.log
I have an application in Angular 7 with many components and many methods in each component.

In every method developers have written console.log('some message ')

Now, I want to override this console.log and append class/component name and method name.

Is there any way to override this and append class name with every log message?

Title: Angular : Override console.log


问:
How to create a signature for bingx api in node js
I want to generate a signature for Bingx website Api

Here's my code:

```<code>const Base64 = require('crypto-js/enc-base64');
const hmacSHA256  = require('crypto-js/hmac-sha256');

let originString = 'POST/api/v1/user/getBalanceapiKey=my_api_key' + '&currency=USDT&timestamp=' + Date.now();
let signature = hmacSHA256(originString, my_secret_key);
signature = Base64.stringify(signature);
signature = encodeURIComponent(signature);
</code>```

I send the signature to the api But I get this error "signature not match"

Here's the bingx api authentication documentation:
link1 and
link2

Body:
I want to generate a signature for Bingx website Api

Here's my code:

const Base64 = require('crypto-js/enc-base64');
const hmacSHA256  = require('crypto-js/hmac-sha256');

let originString = 'POST/api/v1/user/getBalanceapiKey=my_api_key' + '&currency=USDT&timestamp=' + Date.now();
let signature = hmacSHA256(originString, my_secret_key);
signature = Base64.stringify(signature);
signature = encodeURIComponent(signature);

I send the signature to the api But I get this error "signature not match"

Here's the bingx api authentication documentation:
link1 and
link2