问:
Strange bootloader casting issue caused by different packages: "class [Ljava.lang.Object; cannot be cast to class ([Ljava.lang.Object; "
I'm trying to create a nativeQuery in Spring Boot, but I'm getting a strange bootloader message when I try it:

```<code>"class [Ljava.lang.Object; cannot be cast to class com.sick.as.models.common.v1.INorcaSummarySystemDTO ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; com.sick.as.models.common.v1.INorcaSummarySystemDTO is in unnamed module of loader 'app')",
</code>```

Here's the code which triggers the exception:

```<code>@Override
public List<INorcaSummarySystemDTO> getNorcaSummaryBySystem(Long startDate, Long endDate){

Query nativeQuery = this.entityManager.createNativeQuery(norcaSummaryBySystemAndDeviceQuery);
nativeQuery.setParameter("startDate", startDate);
nativeQuery.setParameter("endDate", endDate);

List<INorcaSummarySystemDTO> results =  (List<INorcaSummarySystemDTO>) nativeQuery.getResultList();

for (INorcaSummarySystemDTO  norcaSummarySystemDTO:results) {
    LOG.error(norcaSummarySystemDTO.toString());     <========== exception here
}
</code>```

The exception is generated on the LOG message.

When I hover over the results returned, it shows a list of objects rather than INorcaSummarySystemDTO

```<code>[[Ljava.lang.Object;@9648014, [Ljava.lang.Object;@35cfd4d1, [Ljava.lang.Object;@39be3202, [Ljava.lang.Object;@42efd1c9, [Ljava.lang.Object;@6fa68da0, [Ljava.lang.Object;
</code>```

Based on the error message shown at the start (which is returned to Postman from an API call), there apparently is an issue with the fact that the executing code is getting the DTO from a different bootloader.

For reference, here is the code for the interface and the implementing class:

```<code>package com.sick.as.models.common.v1;

public interface INorcaSummarySystemDTO extends Comparable<INorcaSummarySystemDTO> {

        /**
         * @return system name
         */

        public String getSystemName();

        public void setSystemName(String systemName);

        /**
         * @return system label
         */

        public String getSystemLabel();

        public void setSystemLabel(String systemLabel);

        /**
         * @return Feature Vector
         */
        public Long getFeatureVector();

        public void setFeatureVector(Long featureVector);

        /**
         * @return Norca Code
         */
        public String getNorcaCode();

        public void setNorcaCode(String norcaCode);

        /**
         * @return count
         */

        public Integer getSum();

        public void setSum(Integer sum);

}
</code>```

package com.sick.as.models.common.v1;

import java.util.Comparator;

public class NorcaSummarySystemDTO implements INorcaSummarySystemDTO {

```<code>private String systemName;
private String systemLabel;
private Long featureVector;
private String norcaCode;
private Integer sum;

public NorcaSummarySystemDTO() {
}

    public NorcaSummarySystemDTO(INorcaSummarySystemDTO extractDTO) {
        super();
        this.systemName = extractDTO.getSystemName();
        this.systemLabel = extractDTO.getSystemLabel();
        this.featureVector = extractDTO.getFeatureVector();
        this.norcaCode = extractDTO.getNorcaCode();
        this.sum = extractDTO.getSum();
    }

    public String getSystemName() {
        return systemName;
    }
    public void setSystemName(String systemName) {
        this.systemName = systemName;
    }
    public String getSystemLabel() {
        return systemLabel;
    }
    public void setSystemLabel(String systemLabel) {
        this.systemLabel = systemLabel;
    }
    public Long getFeatureVector() {
        return featureVector;
    }
    public void setFeatureVector(Long featureVector) {
        this.featureVector = featureVector;
    }
    public String getNorcaCode() {
        return norcaCode;
    }
    public void setNorcaCode(String norcaCode) {
        this.norcaCode = norcaCode;
    }
    public Integer getSum() {
        return sum;
    }
    public void setSum(Integer sum) {
        this.sum = sum;
    }

    @Override
    public int compareTo(INorcaSummarySystemDTO o){
        return Comparator.comparing(INorcaSummarySystemDTO::getSystemName)
                  .thenComparing(INorcaSummarySystemDTO::getFeatureVector)
                  .compare(this, o);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((featureVector == null) ? 0 : featureVector.hashCode());
        result = prime * result + ((systemName == null) ? 0 : systemName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        NorcaSummarySystemDTO other = (NorcaSummarySystemDTO) obj;
        if (featureVector == null) {
            if (other.featureVector != null)
                return false;
        } else if (!featureVector.equals(other.featureVector))
            return false;
        if (systemName == null) {
            if (other.systemName != null)
                return false;
        } else if (!systemName.equals(other.systemName))
            return false;
        return true;
    }

}
</code>```

Any ideas what's causing this? The code is based on an example in this url:

```<code>https://thorben-janssen.com/jpa-native-queries/
</code>```

答:
Effectively the reason is that JPA does not know of any way convert the Object that is read, into your desired POJO.

One way you can achieve is to declare your DTO as an @Entity which will ensure that it is JPA managed and then you can call the following overloaded method of createNativeQuery :

```<code>    /**
     * Create an instance of <code>Query</code> for executing
     * a native SQL query.
     * @param sqlString a native SQL query string
     * @param resultClass the class of the resulting instance(s)
     * @return the new query instance
     */
    public Query createNativeQuery(String sqlString, Class resultClass);

    //-----------------
    Query nativeQuery =
    this.entityManager.createNativeQuery(norcaSummaryBySystemAndDeviceQuery, NorcaSummarySystemDTO.class);

</code>```

Once you declare it as an entity there are multiple ways where you can map the result to the DTO.

You can also try one of the manual way , which is get the list and individually initialize the dto by fetching individual records.

```<code>List<Object[]>  results =  nativeQuery.getResultList();
for(Object[] entry: results){
   //init NorcaSummarySystemDTO
   // entry[0] - > set first attribute
   // entry[1] - > set second attribute and so on
}

</code>```

Body:
I'm trying to create a nativeQuery in Spring Boot, but I'm getting a strange bootloader message when I try it:

"class [Ljava.lang.Object; cannot be cast to class com.sick.as.models.common.v1.INorcaSummarySystemDTO ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; com.sick.as.models.common.v1.INorcaSummarySystemDTO is in unnamed module of loader 'app')",

Here's the code which triggers the exception:

@Override
public List<INorcaSummarySystemDTO> getNorcaSummaryBySystem(Long startDate, Long endDate){

Query nativeQuery = this.entityManager.createNativeQuery(norcaSummaryBySystemAndDeviceQuery);
nativeQuery.setParameter("startDate", startDate);
nativeQuery.setParameter("endDate", endDate);

List<INorcaSummarySystemDTO> results =  (List<INorcaSummarySystemDTO>) nativeQuery.getResultList();

for (INorcaSummarySystemDTO  norcaSummarySystemDTO:results) {
    LOG.error(norcaSummarySystemDTO.toString());     <========== exception here
}

The exception is generated on the LOG message.

When I hover over the results returned, it shows a list of objects rather than INorcaSummarySystemDTO

[[Ljava.lang.Object;@9648014, [Ljava.lang.Object;@35cfd4d1, [Ljava.lang.Object;@39be3202, [Ljava.lang.Object;@42efd1c9, [Ljava.lang.Object;@6fa68da0, [Ljava.lang.Object;

Based on the error message shown at the start (which is returned to Postman from an API call), there apparently is an issue with the fact that the executing code is getting the DTO from a different bootloader.

For reference, here is the code for the interface and the implementing class:

package com.sick.as.models.common.v1;

public interface INorcaSummarySystemDTO extends Comparable<INorcaSummarySystemDTO> {

        /**
         * @return system name
         */

        public String getSystemName();

        public void setSystemName(String systemName);

        /**
         * @return system label
         */

        public String getSystemLabel();

        public void setSystemLabel(String systemLabel);

        /**
         * @return Feature Vector
         */
        public Long getFeatureVector();

        public void setFeatureVector(Long featureVector);

        /**
         * @return Norca Code
         */
        public String getNorcaCode();

        public void setNorcaCode(String norcaCode);

        /**
         * @return count
         */

        public Integer getSum();

        public void setSum(Integer sum);

}

package com.sick.as.models.common.v1;

import java.util.Comparator;

public class NorcaSummarySystemDTO implements INorcaSummarySystemDTO {

private String systemName;
private String systemLabel;
private Long featureVector;
private String norcaCode;
private Integer sum;

public NorcaSummarySystemDTO() {
}

    public NorcaSummarySystemDTO(INorcaSummarySystemDTO extractDTO) {
        super();
        this.systemName = extractDTO.getSystemName();
        this.systemLabel = extractDTO.getSystemLabel();
        this.featureVector = extractDTO.getFeatureVector();
        this.norcaCode = extractDTO.getNorcaCode();
        this.sum = extractDTO.getSum();
    }

    public String getSystemName() {
        return systemName;
    }
    public void setSystemName(String systemName) {
        this.systemName = systemName;
    }
    public String getSystemLabel() {
        return systemLabel;
    }
    public void setSystemLabel(String systemLabel) {
        this.systemLabel = systemLabel;
    }
    public Long getFeatureVector() {
        return featureVector;
    }
    public void setFeatureVector(Long featureVector) {
        this.featureVector = featureVector;
    }
    public String getNorcaCode() {
        return norcaCode;
    }
    public void setNorcaCode(String norcaCode) {
        this.norcaCode = norcaCode;
    }
    public Integer getSum() {
        return sum;
    }
    public void setSum(Integer sum) {
        this.sum = sum;
    }

    @Override
    public int compareTo(INorcaSummarySystemDTO o){
        return Comparator.comparing(INorcaSummarySystemDTO::getSystemName)
                  .thenComparing(INorcaSummarySystemDTO::getFeatureVector)
                  .compare(this, o);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((featureVector == null) ? 0 : featureVector.hashCode());
        result = prime * result + ((systemName == null) ? 0 : systemName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        NorcaSummarySystemDTO other = (NorcaSummarySystemDTO) obj;
        if (featureVector == null) {
            if (other.featureVector != null)
                return false;
        } else if (!featureVector.equals(other.featureVector))
            return false;
        if (systemName == null) {
            if (other.systemName != null)
                return false;
        } else if (!systemName.equals(other.systemName))
            return false;
        return true;
    }

}

Any ideas what's causing this? The code is based on an example in this url:

https://thorben-janssen.com/jpa-native-queries/

Body:
Effectively the reason is that JPA does not know of any way convert the Object that is read, into your desired POJO.

One way you can achieve is to declare your DTO as an @Entity which will ensure that it is JPA managed and then you can call the following overloaded method of createNativeQuery :

    /**
     * Create an instance of <code>Query</code> for executing
     * a native SQL query.
     * @param sqlString a native SQL query string
     * @param resultClass the class of the resulting instance(s)
     * @return the new query instance
     */
    public Query createNativeQuery(String sqlString, Class resultClass);

    //-----------------
    Query nativeQuery =
    this.entityManager.createNativeQuery(norcaSummaryBySystemAndDeviceQuery, NorcaSummarySystemDTO.class);

Once you declare it as an entity there are multiple ways where you can map the result to the DTO.

You can also try one of the manual way , which is get the list and individually initialize the dto by fetching individual records.

List<Object[]>  results =  nativeQuery.getResultList();
for(Object[] entry: results){
   //init NorcaSummarySystemDTO
   // entry[0] - > set first attribute
   // entry[1] - > set second attribute and so on
}


来源: stackexchange

问:
Convert words (string) to Int
I'm sure this has been done a hundred times, but i'm hoping there is a really simple way to accomplished this.  I'm wanting to change words to an int.

Like the following example

```One = 1
Two = 2
Three = 3
```

So basically if I have the string "One" it gets converted to 1, even if I could get back a string "1" I can just convert that.

答:
I think a far easier to understand solution is as follows:</p>
```<code>public static int ParseInt(string s)
{
  var wordArray = s.Split(' ', '-');
  int finalNumber = 0;

  Dictionary<string, int> additionWords = new Dictionary<string, int>{
    {"one" , 1}, {"two", 2},{"three", 3},{"four", 4},{"five", 5},{"six", 6},
    {"seven", 7},{"eight", 8},{"nine", 9},{"ten", 10},{"eleven", 11},{"twelve", 12},
    {"thirteen", 13},{"fourteen", 14},{"fifteen", 15},{"sixteen", 16},{"seventeen", 17},
    {"eighteen", 18},{"nineteen", 19},{"twenty", 20},{"thirty", 30},{"forty", 40},
    {"fifty", 50},{"sixty", 60},{"seventy", 70},{"eighty", 80},{"ninety", 90}
  };

  Dictionary<string, int> multiplicationWords = new Dictionary<string, int>{
    {"hundred", 100},{"thousand", 1000},{"million", 1000000}
  };

  int multiplier = 1;

  for (int i = wordArray.Length - 1; i >= 0; i--){
    if (additionWords.ContainsKey(wordArray[i])){
      finalNumber += additionWords[wordArray[i]] * multiplier;
    }
    if (multiplicationWords.ContainsKey(wordArray[i])){
      if (multiplicationWords[wordArray[i]] < multiplier){
        multiplier *= multiplicationWords[wordArray[i]];
      }else{
        multiplier = multiplicationWords[wordArray[i]];
      }
    }
  }
  return finalNumber;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert words (string) to Int

Body:
I'm sure this has been done a hundred times, but i'm hoping there is a really simple way to accomplished this.  I'm wanting to change words to an int.

Like the following example

One = 1
Two = 2
Three = 3

So basically if I have the string "One" it gets converted to 1, even if I could get back a string "1" I can just convert that.

Body:
I think a far easier to understand solution is as follows:

public static int ParseInt(string s)
{
  var wordArray = s.Split(' ', '-');
  int finalNumber = 0;

  Dictionary<string, int> additionWords = new Dictionary<string, int>{
    {"one" , 1}, {"two", 2},{"three", 3},{"four", 4},{"five", 5},{"six", 6},
    {"seven", 7},{"eight", 8},{"nine", 9},{"ten", 10},{"eleven", 11},{"twelve", 12},
    {"thirteen", 13},{"fourteen", 14},{"fifteen", 15},{"sixteen", 16},{"seventeen", 17},
    {"eighteen", 18},{"nineteen", 19},{"twenty", 20},{"thirty", 30},{"forty", 40},
    {"fifty", 50},{"sixty", 60},{"seventy", 70},{"eighty", 80},{"ninety", 90}
  };

  Dictionary<string, int> multiplicationWords = new Dictionary<string, int>{
    {"hundred", 100},{"thousand", 1000},{"million", 1000000}
  };

  int multiplier = 1;

  for (int i = wordArray.Length - 1; i >= 0; i--){
    if (additionWords.ContainsKey(wordArray[i])){
      finalNumber += additionWords[wordArray[i]] * multiplier;
    }
    if (multiplicationWords.ContainsKey(wordArray[i])){
      if (multiplicationWords[wordArray[i]] < multiplier){
        multiplier *= multiplicationWords[wordArray[i]];
      }else{
        multiplier = multiplicationWords[wordArray[i]];
      }
    }
  }
  return finalNumber;
}

ContentLicense: CC BY-SA 4.0


问:
How to convert time format to a number format (Google Sheets/Data Studio)
I want to convert the numbers in ColA to normal numbers, like the ones I have in ColB. The one in ColA currently are in this format: 00:56:00.000. I initially started out with a time length, that I then converted to seconds (what's currently in ColA). I need to convert them back into a single number to import into Data Studio so it can read it as time. If I try to change the formatting to a number it comes up as a decimal, how can I change the format to a number? Or can I do it in Data Studio?

https://docs.google.com/spreadsheets/d/1xaAfc6hcFJJ1JsPfrx9Ly3usfljuzELT80UsgSxcNM8/edit#gid=0

答:
Try this on col B3 on Google Sheets while A3:A is converted into number format (in decimals):

```<code>=Arrayformula((A3:A*3600)*24)
</code>```

Output:

Explanation:

This is just an observation, but it seems that Google Data Studio strictly follows the formatting of the cell values. If you want to read the seconds as integers, a few arithmetic operations was performed to convert the number formatting of duration as such presented above.

Apps Script (use this if removing helper column B):

```<code>function myFunction() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var data = ss.getRange('A3:A').getValues();

  Logger.log(data);

  var second = 3600;
  var hour = 24;
  var output = data.map(x => [x[0] * second * hour]);
  ss.getActiveSheet().getRange(3, 1, output.length, output[0].length).setValues(output);
}
</code>```

Output:

Body:
Try this on col B3 on Google Sheets while A3:A is converted into number format (in decimals):

=Arrayformula((A3:A*3600)*24)

Output:

Explanation:

This is just an observation, but it seems that Google Data Studio strictly follows the formatting of the cell values. If you want to read the seconds as integers, a few arithmetic operations was performed to convert the number formatting of duration as such presented above.

Apps Script (use this if removing helper column B):

function myFunction() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var data = ss.getRange('A3:A').getValues();

  Logger.log(data);

  var second = 3600;
  var hour = 24;
  var output = data.map(x => [x[0] * second * hour]);
  ss.getActiveSheet().getRange(3, 1, output.length, output[0].length).setValues(output);
}

Output:


问:
Insert a value in a slice at a given index
Given

```<code>array1 := []int{1, 3, 4, 5}
array2 := []int{2, 4, 6, 8}
</code>```

I want to insert array2[2] i.e 6 at array1[1] i.e before 3 so that array1 becomes a slice of {1, 6, 3, 4, 5}. How can I do it?

Most the techniques I read online involve using the : operator but results in remaining elements being inserted as well. How can I append single values at an index in a slice?

答:
Here a one-liner:

```<code>append(array1[:1], append(array2[2:3], array1[1:]...)...)
</code>```

Go Playground

Body:
Given

array1 := []int{1, 3, 4, 5}
array2 := []int{2, 4, 6, 8}

I want to insert array2[2] i.e 6 at array1[1] i.e before 3 so that array1 becomes a slice of {1, 6, 3, 4, 5}. How can I do it?

Most the techniques I read online involve using the : operator but results in remaining elements being inserted as well. How can I append single values at an index in a slice?

Body:
Here a one-liner:

append(array1[:1], append(array2[2:3], array1[1:]...)...)

Go Playground


问:
PSQL passing external variables
I'm trying to pass a value/variable from a batch script to a SQL script and I am having trouble.

The code flows as such:

Starting in my batch script, I make a psql command call referencing myFirstSQLFile.sql, and passing env as a variable with a value of test

```<code>%PSQLCOMMAND% -h {server} -U {user} -d {dbname} -E -q -f myFirstSQLFile.sql -v env="test"
</code>```

In my myFirstSQLFile.sql, it makes references to a number of other sql files, but I'll just show one for simplicity. It is in this file that I know I can access my env variable by using :env

```<code>\i myLastSQLFile.sql;
</code>```

Within myLastSQLFile.sql, I have sql code that is meant to use that external env var for conditional statements as below

```<code>DO
$do$
BEGIN
   IF :env = 'test' THEN
       # Do Something
   END IF;
END
$do$
</code>```

I know outside of those $do$ tags, I can access my variable by using the notation :env, However within them I cannot. I don't really understand what the $do$ tags or the BEGIN/END block are for and if/how I can access my env variable within them.

答:
A DO statement executes an anonymous code block. The "$do$ tags" are dollar-quotes. Read this first to understand:

What are '$$' used for in PL/pgSQL

BEGINand END are decorators for a PL/pgSQL code block - which is the default PL (programming language) of a DO statement.

psql does not interpolate variables inside quoted SQL literals and identifiers.

One way to fix your problem is using Postgres string processing and then execute the result with \gexec. From psql:

SELECT format($$
DO
$do$
BEGIN
   IF %L = 'test' THEN
      -- do something
   END IF;
END
$do$;
$$, :'env')\gexec
```

There are various other ways. Maybe a (temporary) function can serve you better: you can pass parameters to it. Depends on the complete picture.

See this answers to a very similar question on dba.SE:

How to pass variable to PL/pgSQL code from the command line?

Title: PSQL passing external variables

Body:
I'm trying to pass a value/variable from a batch script to a SQL script and I am having trouble.

The code flows as such:

Starting in my batch script, I make a psql command call referencing myFirstSQLFile.sql, and passing env as a variable with a value of test

%PSQLCOMMAND% -h {server} -U {user} -d {dbname} -E -q -f myFirstSQLFile.sql -v env="test"

In my myFirstSQLFile.sql, it makes references to a number of other sql files, but I'll just show one for simplicity. It is in this file that I know I can access my env variable by using :env

\i myLastSQLFile.sql;

Within myLastSQLFile.sql, I have sql code that is meant to use that external env var for conditional statements as below

DO
$do$
BEGIN
   IF :env = 'test' THEN
       # Do Something
   END IF;
END
$do$

I know outside of those $do$ tags, I can access my variable by using the notation :env, However within them I cannot. I don't really understand what the $do$ tags or the BEGIN/END block are for and if/how I can access my env variable within them.

Body:
A DO statement executes an anonymous code block. The "$do$ tags" are dollar-quotes. Read this first to understand:

What are '$$' used for in PL/pgSQL

BEGINand END are decorators for a PL/pgSQL code block - which is the default PL (programming language) of a DO statement.

psql does not interpolate variables inside quoted SQL literals and identifiers.

One way to fix your problem is using Postgres string processing and then execute the result with \gexec. From psql:

SELECT format($$
DO
$do$
BEGIN
   IF %L = 'test' THEN
      -- do something
   END IF;
END
$do$;
$$, :'env')\gexec

There are various other ways. Maybe a (temporary) function can serve you better: you can pass parameters to it. Depends on the complete picture.

See this answers to a very similar question on dba.SE:

How to pass variable to PL/pgSQL code from the command line?


问:
'ActionRow' object has no attribute 'get'
I'm trying to send a message with buttons, but it gives an error

Before that, the code was in one file and worked, but as soon as I wanted to move everything to cog, this error came out

```<code>  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/client.py", line 1353, in invoke_command
    await func.invoke(ctx, **args)
  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/model.py", line 209, in invoke
    return await self.func(self.cog, *args, **kwargs)
  File "/home/bot/cogs/controlpanel.py", line 68, in clear
    await ctx.send(embed=emb, components=[row])
  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/context.py", line 215, in send
    if components and not all(comp.get("type") == 1 for comp in components):
  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/context.py", line 215, in <genexpr>
    if components and not all(comp.get("type") == 1 for comp in components):
AttributeError: 'ActionRow' object has no attribute 'get'
</code>```

My code:

class Controlpanel(commands.Cog):
   def __init__(self, bot):
       self.bot = bot

   @cog_ext.cog_slash(name='controlpanel', description='Разместить панель управления сервером',
                guild_ids=[928666080929542194])
   @commands.has_permissions(administrator=True)
   async def clear(self, ctx: SlashContext):
       emb = discord.Embed(
           description =
           f"""
           Панель управления сервером через дискорд
           """,
           colour = 0xffba42
       )
       emb.set_author(name='Панель управления')

       row = ActionRow(
           Button(
               style=ButtonStyle.grey,
               label='Статус',
               custom_id='status'
           ),
           Button(
               style=ButtonStyle.green,
               label='Запуск',
               custom_id='on'
           ),
           Button(
               style=ButtonStyle.red,
               label='Выключить',
               custom_id='off'
           ),
           Button(
               style=ButtonStyle.green,
               label='Перезапуск',
               custom_id='restart'
           ),
           Button(
               style=ButtonStyle.red,
               label='Убить',
               custom_id='kill'
           )
       )
       await ctx.send(embed=emb, components=[row])

   @commands.Cog.listener()
   async def on_button_click(self, inter):
       if inter.component.id == "status":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver status"
           stdin, stdout, stderr = ssh.exec_command(command)
           lines = stdout.readlines()
           str1 = ''.join(lines)
           print(time() + ' - ' + str1)
           ssh.close()
           await inter.reply(str1, ephemeral = True)
       if inter.component.id == "on":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver start"
           ssh.exec_command(command)
           ssh.close()
           await inter.reply('Запускаю сервер! ', ephemeral = True)
       if inter.component.id == "off":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver stop"
           ssh.exec_command(command)
           ssh.close()
           await inter.reply('Выключаю сервер! ', ephemeral = True)
       if inter.component.id == "kill":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver kill"
           stdin, stdout, stderr = ssh.exec_command(command)
           lines = stdout.readlines()
           str1 = ''.join(lines)
           print(time() + ' - ' + str1)
           ssh.close()
           await inter.reply(str1, ephemeral = True)
       if inter.component.id == "restart":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver restart"
           ssh.exec_command(command)
           ssh.close()
           await inter.reply('Перезапускаю сервер! ', ephemeral = True)
           my_channel = self.bot.get_channel(936698972561637496)
           emb = discord.Embed(
               description =
               f"""
               Сервер перезапуститься через 15 минут.
               """,
               colour = 0xffba42
           )
           emb.set_author(name = 'Перезапуск сервера!')
           await my_channel.send(embed = emb)

def setup(bot):
   bot.add_cog(Controlpanel(bot))
```

答:
from discord_slash.utils.manage_components import create_actionrow, create_button

@cog_ext.cog_slash(name='controlpanel', description='Разместить панель управления сервером',
             guild_ids=[928666080929542194])
@commands.has_permissions(administrator=True)
async def clear(self, ctx: SlashContext):
    emb = discord.Embed(
        description =
        f"""
        Панель управления сервером через дискорд
        """,
        colour = 0xffba42
    )
    emb.set_author(name='Панель управления')

    row = create_actionrow(*[
        create_button(
            style=ButtonStyle.grey,
            label='Статус',
            custom_id='status'
        ),
        create_button(
            style=ButtonStyle.green,
            label='Запуск',
            custom_id='on'
        ),
        create_button(
            style=ButtonStyle.red,
            label='Выключить',
            custom_id='off'
        ),
        create_button(
            style=ButtonStyle.green,
            label='Перезапуск',
            custom_id='restart'
        ),
        create_button(
            style=ButtonStyle.red,
            label='Убить',
            custom_id='kill'
        )
    ])
    await ctx.send(embed=emb, components=[row])
```

components should be delivered in the form of a dict.

If you use interaction.py 4.0.0~, you can use from interactions.models.component import ActionRow module github

Body:
I'm trying to send a message with buttons, but it gives an error

Before that, the code was in one file and worked, but as soon as I wanted to move everything to cog, this error came out

  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/client.py", line 1353, in invoke_command
    await func.invoke(ctx, **args)
  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/model.py", line 209, in invoke
    return await self.func(self.cog, *args, **kwargs)
  File "/home/bot/cogs/controlpanel.py", line 68, in clear
    await ctx.send(embed=emb, components=[row])
  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/context.py", line 215, in send
    if components and not all(comp.get("type") == 1 for comp in components):
  File "/home/bot/.local/lib/python3.8/site-packages/discord_slash/context.py", line 215, in <genexpr>
    if components and not all(comp.get("type") == 1 for comp in components):
AttributeError: 'ActionRow' object has no attribute 'get'

My code:

class Controlpanel(commands.Cog):
   def __init__(self, bot):
       self.bot = bot

   @cog_ext.cog_slash(name='controlpanel', description='Разместить панель управления сервером',
                guild_ids=[928666080929542194])
   @commands.has_permissions(administrator=True)
   async def clear(self, ctx: SlashContext):
       emb = discord.Embed(
           description =
           f"""
           Панель управления сервером через дискорд
           """,
           colour = 0xffba42
       )
       emb.set_author(name='Панель управления')

       row = ActionRow(
           Button(
               style=ButtonStyle.grey,
               label='Статус',
               custom_id='status'
           ),
           Button(
               style=ButtonStyle.green,
               label='Запуск',
               custom_id='on'
           ),
           Button(
               style=ButtonStyle.red,
               label='Выключить',
               custom_id='off'
           ),
           Button(
               style=ButtonStyle.green,
               label='Перезапуск',
               custom_id='restart'
           ),
           Button(
               style=ButtonStyle.red,
               label='Убить',
               custom_id='kill'
           )
       )
       await ctx.send(embed=emb, components=[row])

   @commands.Cog.listener()
   async def on_button_click(self, inter):
       if inter.component.id == "status":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver status"
           stdin, stdout, stderr = ssh.exec_command(command)
           lines = stdout.readlines()
           str1 = ''.join(lines)
           print(time() + ' - ' + str1)
           ssh.close()
           await inter.reply(str1, ephemeral = True)
       if inter.component.id == "on":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver start"
           ssh.exec_command(command)
           ssh.close()
           await inter.reply('Запускаю сервер! ', ephemeral = True)
       if inter.component.id == "off":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver stop"
           ssh.exec_command(command)
           ssh.close()
           await inter.reply('Выключаю сервер! ', ephemeral = True)
       if inter.component.id == "kill":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver kill"
           stdin, stdout, stderr = ssh.exec_command(command)
           lines = stdout.readlines()
           str1 = ''.join(lines)
           print(time() + ' - ' + str1)
           ssh.close()
           await inter.reply(str1, ephemeral = True)
       if inter.component.id == "restart":
           ssh = paramiko.SSHClient()
           ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
           ssh.connect(host, port, username, password)
           command = "pzserver restart"
           ssh.exec_command(command)
           ssh.close()
           await inter.reply('Перезапускаю сервер! ', ephemeral = True)
           my_channel = self.bot.get_channel(936698972561637496)
           emb = discord.Embed(
               description =
               f"""
               Сервер перезапуститься через 15 минут.
               """,
               colour = 0xffba42
           )
           emb.set_author(name = 'Перезапуск сервера!')
           await my_channel.send(embed = emb)

def setup(bot):
   bot.add_cog(Controlpanel(bot))

Body:
from discord_slash.utils.manage_components import create_actionrow, create_button

@cog_ext.cog_slash(name='controlpanel', description='Разместить панель управления сервером',
             guild_ids=[928666080929542194])
@commands.has_permissions(administrator=True)
async def clear(self, ctx: SlashContext):
    emb = discord.Embed(
        description =
        f"""
        Панель управления сервером через дискорд
        """,
        colour = 0xffba42
    )
    emb.set_author(name='Панель управления')

    row = create_actionrow(*[
        create_button(
            style=ButtonStyle.grey,
            label='Статус',
            custom_id='status'
        ),
        create_button(
            style=ButtonStyle.green,
            label='Запуск',
            custom_id='on'
        ),
        create_button(
            style=ButtonStyle.red,
            label='Выключить',
            custom_id='off'
        ),
        create_button(
            style=ButtonStyle.green,
            label='Перезапуск',
            custom_id='restart'
        ),
        create_button(
            style=ButtonStyle.red,
            label='Убить',
            custom_id='kill'
        )
    ])
    await ctx.send(embed=emb, components=[row])

components should be delivered in the form of a dict.

If you use interaction.py 4.0.0~, you can use from interactions.models.component import ActionRow module github


问:
text-break, word-break, all breaks do not work anymore for no apparent reason
I had this issue fixed with text-break from bootstrap, but for some reason, something is overriding it and now my text does not wrap at all. I put a code snippet that reproduces the issue. I've tried everything and I am sure I am missing something silly. I'm only typing now because stackoverflow wants me to. You can ignore the next set of random thoughts.

.comment_input{
    padding: 5px;
    margin: 5px;
    border-radius: 8px;
    border: none;
    width: 100%;
}

.profile-name{
    display: flex;
    align-items: center;
    column-gap: 5px;
}

.profile_image{
    width: 30px;
    height: 30px;
    border-radius: 50%;
}

.post{
    margin: 10px auto;
    width: 80%;
    border-radius: 3px;
    background: darkgray;
}

.post_padding{
    margin: 5px;
}

.post_comment{
    display: flex;
    align-items: center;
    gap: 5px;
}

.post_top{
    display: flex;
    justify-content: space-between;
}

.hover:hover {
    cursor: pointer;
}

.like-and-comment{
    display: flex;
    justify-content: space-around;
    border-bottom: 1px solid white;
    border-top: 1px solid white;
    align-items: center;
    padding: 5px;
}

.view-more{
    display: flex;
    justify-content: space-between;
    font-size: 14px;
}

.lk{
    display: flex;
    font-size: 14px;
    gap: 5px;
}

.right{
    border-left: 1px solid white;
    border-bottom: 1px solid white;
    border-bottom-left-radius: 30px;
    width: 5%;
    top: 5px;
    position: absolute;
    height: 120%;
    left: -20px;
}

.reply {
    display: flex;
    gap: 10px;
}

.reply-body{
    word-wrap    : break-word;
    overflow-wrap: break-word;
}

.user{
    /* TODO fix text overflow for when no spaces added*/
    background: grey;
    padding: 8px;
    border-radius: 20px;
    /*TODO max variable based on content*/
    width: max-content;
    word-wrap    : break-word;
    overflow-wrap: break-word;
}

.like-comment, .reply_comment{
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <!-- CSS only -->
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
      <link href="/static/css/style.css" rel="stylesheet">
      <script src="https://js.stripe.com/v3/"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
    </head>
<body>

<div class="post">
      <script id="counter40">1</script>
      <div class="post_padding">
        <div class="post_top">
          <div class="profile-name">
            <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
            <div>
              <div id="post_top"> jon </div>
              <div id="post_top2" class="location-time"><span class="time">in 3 hours</span><i class="fas fa-globe-americas"></i></div>
            </div>
          </div>
          <div id="three-dots" style="display: block" class="hover">
            <div class="dropdown">
              <div href="#" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></div>
              <div class="dropdown-menu">
                <div id="post_edit_modal" style="display: block" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_edit_modal(40)">
                  <i class="bi bi-pencil-square"> Edit</i>
                </div>

                <div id="post_ban_modal" style="display: block" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_ban_modal(1)">
                  <i class="bi bi-eye-slash"> Ban</i>
                </div>
                <div id="post_history_modal" style="display: none;" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_history_modal(1)">
                  <i class="bi bi-clock-history"> History</i>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!--this is really the post-->
        <div class="media ">
          <div class="text-break" id="post_body">hi</div>
          <img id="media_graphic">
        </div>

        <!--Finish this, need media link, media article-->

        <div class="like-and-comment">
          <div class="d-flex align-items-center">
            <i id="upvote40" class="fas fa-arrow-up hover" style="color: gray;" onclick="vote(40,1)"></i>
            <span id="upvote_count_badge40" class="badge bg-secondary">0</span>
            <i id="downvote40" class="fas fa-arrow-down hover" style="color: gray;" onclick="vote(40,0)"></i>
          </div>

          <div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_award_modal(40)">
              <i class="fas fa-award hover"></i>
          </div>

          <div class="dropdown hover">
            <div class="dropdown-toggle" data-bs-toggle="dropdown"><i class="fas fa-share"></i></div>
            <ul class="dropdown-menu">
              <p id="post_crosspost_modal" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_crosspost_modal(40)">
                <i class="bi bi-signpost-2"> Cross Post</i>
              </p>
              <p id="copytoclipboard" class="dropdown-item" onclick="copyToClipboard('http://127.0.0.1:5000/post/40')">
                <i class="bi bi-clipboard"> Copy Link</i>
              </p>
              <p id="save_post" class="dropdown-item" onclick="save_post(40)">
                <i id="save_post_icon40" class="bi bi-save"> Save</i>
              </p>
            </ul>
          </div>
        </div>

        <div class="view-more">
          <div class="hover" id="load_replies40" onclick="loadReplies(40,0)"></div>
          <div class="hover" id="comment_collapse"> 1 comments</div>
        </div>

        <div class="comment">
          <div id="reply_loader40"><!--Append Replies Here-->
  <div class="lk">
    <script id="counter46">0</script>
    <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
    <div style="width: 100%;">
      <div class="user">
        <div class="reply_author">jon in 6 hours </div>
        <div class="reply-body">word-wrap    : break-word; overflow-wrap: break-word;word-wrap    : break-word; overflow-wrap: break-word;word-wrap    : break-word; overflow-wrap: break-word;word-wrap    : break-word; overflow-wrap: break-word;</div>
      </div>
      <div class="reply">
        <div class="d-flex align-items-center">
          <i id="upvote46" class="fas fa-arrow-up hover" style="color: gray" onclick="vote(46,1)"></i>
          <span id="upvote_count_badge46" class="badge bg-secondary">0</span>
          <i id="downvote46" class="fas fa-arrow-down hover" style="color: gray" onclick="vote(46,0)"></i>
        </div>
        <div class="reply_comment" id="reply46">Reply</div>
        <div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_award_modal(46)">
            <i class="fas fa-award hover"></i>
        </div>
      </div>

      <form id="submit_reply46" style="display: none;" autocomplete="off">
        <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
        <input class="comment_input" id="comment_input46" maxlength="1024" name="body" placeholder="Write a comment3" required="" type="text" value="">
        <div id="comment_input_error46" class="invalid-feedback"></div>
      </form>
      <div id="reply_loader46"><!--Nested Replies go here--></div>
    </div>
  </div>
</div>

          <form id="submit_reply" autocomplete="off">
            <div class="post_comment">
              <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
              <input class="comment_input" id="comment_input40" maxlength="1024" name="body" placeholder="Write a comment" required="" type="text" value="">
              <div id="comment_input_error40" class="invalid-feedback"></div>
            </div>
          </form>
        </div>
      </div>
    </div>

    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

</body></code>```

答:
You used max-content for your width in your user container.

The max-content sizing keyword represents the intrinsic maximum width or height of the content. For text content this means that the content will not wrap at all even if it causes overflows. -MDN

You can change that to 100%. You can learn more on max-content here.

.comment_input {
  padding: 5px;
  margin: 5px;
  border-radius: 8px;
  border: none;
  width: 100%;
}

.profile-name {
  display: flex;
  align-items: center;
  column-gap: 5px;
}

.profile_image {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.post {
  margin: 10px auto;
  width: 80%;
  border-radius: 3px;
  background: darkgray;
}

.post_padding {
  margin: 5px;
}

.post_comment {
  display: flex;
  align-items: center;
  gap: 5px;
}

.post_top {
  display: flex;
  justify-content: space-between;
}

.hover:hover {
  cursor: pointer;
}

.like-and-comment {
  display: flex;
  justify-content: space-around;
  border-bottom: 1px solid white;
  border-top: 1px solid white;
  align-items: center;
  padding: 5px;
}

.view-more {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.lk {
  display: flex;
  font-size: 14px;
  gap: 5px;
}

.right {
  border-left: 1px solid white;
  border-bottom: 1px solid white;
  border-bottom-left-radius: 30px;
  width: 5%;
  top: 5px;
  position: absolute;
  height: 120%;
  left: -20px;
}

.reply {
  display: flex;
  gap: 10px;
}

.reply-body {
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.user {
  /* TODO fix text overflow for when no spaces added*/
  background: grey;
  padding: 8px;
  border-radius: 20px;
  /*TODO max variable based on content*/
  width: 100%;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.like-comment,
.reply_comment {
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- CSS only -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
  <link href="/static/css/style.css" rel="stylesheet">
  <script src="https://js.stripe.com/v3/"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>

<body>

  <div class="post">
    <script id="counter40">
      1
    </script>
    <div class="post_padding">
      <div class="post_top">
        <div class="profile-name">
          <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
          <div>
            <div id="post_top"> jon </div>
            <div id="post_top2" class="location-time"><span class="time">in 3 hours</span><i class="fas fa-globe-americas"></i></div>
          </div>
        </div>
        <div id="three-dots" style="display: block" class="hover">
          <div class="dropdown">
            <div href="#" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></div>
            <div class="dropdown-menu">
              <div id="post_edit_modal" style="display: block" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_edit_modal(40)">
                <i class="bi bi-pencil-square"> Edit</i>
              </div>

              <div id="post_ban_modal" style="display: block" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_ban_modal(1)">
                <i class="bi bi-eye-slash"> Ban</i>
              </div>
              <div id="post_history_modal" style="display: none;" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_history_modal(1)">
                <i class="bi bi-clock-history"> History</i>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!--this is really the post-->
      <div class="media ">
        <div class="text-break" id="post_body">hi</div>
        <img id="media_graphic">
      </div>

      <!--Finish this, need media link, media article-->

      <div class="like-and-comment">
        <div class="d-flex align-items-center">
          <i id="upvote40" class="fas fa-arrow-up hover" style="color: gray;" onclick="vote(40,1)"></i>
          <span id="upvote_count_badge40" class="badge bg-secondary">0</span>
          <i id="downvote40" class="fas fa-arrow-down hover" style="color: gray;" onclick="vote(40,0)"></i>
        </div>

        <div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_award_modal(40)">
          <i class="fas fa-award hover"></i>
        </div>

        <div class="dropdown hover">
          <div class="dropdown-toggle" data-bs-toggle="dropdown"><i class="fas fa-share"></i></div>
          <ul class="dropdown-menu">
            <p id="post_crosspost_modal" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_crosspost_modal(40)">
              <i class="bi bi-signpost-2"> Cross Post</i>
            </p>
            <p id="copytoclipboard" class="dropdown-item" onclick="copyToClipboard('http://127.0.0.1:5000/post/40')">
              <i class="bi bi-clipboard"> Copy Link</i>
            </p>
            <p id="save_post" class="dropdown-item" onclick="save_post(40)">
              <i id="save_post_icon40" class="bi bi-save"> Save</i>
            </p>
          </ul>
        </div>
      </div>

      <div class="view-more">
        <div class="hover" id="load_replies40" onclick="loadReplies(40,0)"></div>
        <div class="hover" id="comment_collapse"> 1 comments</div>
      </div>

      <div class="comment">
        <div id="reply_loader40">
          <!--Append Replies Here-->
          <div class="lk">
            <script id="counter46">
              0
            </script>
            <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
            <div style="width: 100%;">
              <div class="user">
                <div class="reply_author">jon in 6 hours </div>
                <div class="reply-body">word-wrap : break-word; overflow-wrap: break-word;word-wrap : break-word; overflow-wrap: break-word;word-wrap : break-word; overflow-wrap: break-word;word-wrap : break-word; overflow-wrap: break-word;</div>
              </div>
              <div class="reply">
                <div class="d-flex align-items-center">
                  <i id="upvote46" class="fas fa-arrow-up hover" style="color: gray" onclick="vote(46,1)"></i>
                  <span id="upvote_count_badge46" class="badge bg-secondary">0</span>
                  <i id="downvote46" class="fas fa-arrow-down hover" style="color: gray" onclick="vote(46,0)"></i>
                </div>
                <div class="reply_comment" id="reply46">Reply</div>
                <div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_award_modal(46)">
                  <i class="fas fa-award hover"></i>
                </div>
              </div>

              <form id="submit_reply46" style="display: none;" autocomplete="off">
                <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
                <input class="comment_input" id="comment_input46" maxlength="1024" name="body" placeholder="Write a comment3" required="" type="text" value="">
                <div id="comment_input_error46" class="invalid-feedback"></div>
              </form>
              <div id="reply_loader46">
                <!--Nested Replies go here-->
              </div>
            </div>
          </div>
        </div>

        <form id="submit_reply" autocomplete="off">
          <div class="post_comment">
            <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
            <input class="comment_input" id="comment_input40" maxlength="1024" name="body" placeholder="Write a comment" required="" type="text" value="">
            <div id="comment_input_error40" class="invalid-feedback"></div>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

</body></code>```

Body:
I had this issue fixed with text-break from bootstrap, but for some reason, something is overriding it and now my text does not wrap at all. I put a code snippet that reproduces the issue. I've tried everything and I am sure I am missing something silly. I'm only typing now because stackoverflow wants me to. You can ignore the next set of random thoughts.

.comment_input{
    padding: 5px;
    margin: 5px;
    border-radius: 8px;
    border: none;
    width: 100%;
}

.profile-name{
    display: flex;
    align-items: center;
    column-gap: 5px;
}

.profile_image{
    width: 30px;
    height: 30px;
    border-radius: 50%;
}

.post{
    margin: 10px auto;
    width: 80%;
    border-radius: 3px;
    background: darkgray;
}

.post_padding{
    margin: 5px;
}

.post_comment{
    display: flex;
    align-items: center;
    gap: 5px;
}

.post_top{
    display: flex;
    justify-content: space-between;
}

.hover:hover {
    cursor: pointer;
}

.like-and-comment{
    display: flex;
    justify-content: space-around;
    border-bottom: 1px solid white;
    border-top: 1px solid white;
    align-items: center;
    padding: 5px;
}

.view-more{
    display: flex;
    justify-content: space-between;
    font-size: 14px;
}

.lk{
    display: flex;
    font-size: 14px;
    gap: 5px;
}

.right{
    border-left: 1px solid white;
    border-bottom: 1px solid white;
    border-bottom-left-radius: 30px;
    width: 5%;
    top: 5px;
    position: absolute;
    height: 120%;
    left: -20px;
}

.reply {
    display: flex;
    gap: 10px;
}

.reply-body{
    word-wrap    : break-word;
    overflow-wrap: break-word;
}

.user{
    /* TODO fix text overflow for when no spaces added*/
    background: grey;
    padding: 8px;
    border-radius: 20px;
    /*TODO max variable based on content*/
    width: max-content;
    word-wrap    : break-word;
    overflow-wrap: break-word;
}

.like-comment, .reply_comment{
    cursor: pointer;
}

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
      <link href="/static/css/style.css" rel="stylesheet">

      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

 jon

in 3 hours

                   Edit

                   Ban

                   History

hi

            0

                 Cross Post

                 Copy Link

                 Save

 1 comments

jon in 6 hours

word-wrap    : break-word; overflow-wrap: break-word;word-wrap    : break-word; overflow-wrap: break-word;word-wrap    : break-word; overflow-wrap: break-word;word-wrap    : break-word; overflow-wrap: break-word;

          0

Reply

      <form id="submit_reply46" style="display: none;" autocomplete="off">

        <input class="comment_input" id="comment_input46" maxlength="1024" name="body" placeholder="Write a comment3" required="" type="text" value="">

      </form>

          <form id="submit_reply" autocomplete="off">

              <input class="comment_input" id="comment_input40" maxlength="1024" name="body" placeholder="Write a comment" required="" type="text" value="">

          </form>

Body:
You used max-content for your width in your user container.

The max-content sizing keyword represents the intrinsic maximum width or height of the content. For text content this means that the content will not wrap at all even if it causes overflows. -MDN

You can change that to 100%. You can learn more on max-content here.

.comment_input {
  padding: 5px;
  margin: 5px;
  border-radius: 8px;
  border: none;
  width: 100%;
}

.profile-name {
  display: flex;
  align-items: center;
  column-gap: 5px;
}

.profile_image {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.post {
  margin: 10px auto;
  width: 80%;
  border-radius: 3px;
  background: darkgray;
}

.post_padding {
  margin: 5px;
}

.post_comment {
  display: flex;
  align-items: center;
  gap: 5px;
}

.post_top {
  display: flex;
  justify-content: space-between;
}

.hover:hover {
  cursor: pointer;
}

.like-and-comment {
  display: flex;
  justify-content: space-around;
  border-bottom: 1px solid white;
  border-top: 1px solid white;
  align-items: center;
  padding: 5px;
}

.view-more {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.lk {
  display: flex;
  font-size: 14px;
  gap: 5px;
}

.right {
  border-left: 1px solid white;
  border-bottom: 1px solid white;
  border-bottom-left-radius: 30px;
  width: 5%;
  top: 5px;
  position: absolute;
  height: 120%;
  left: -20px;
}

.reply {
  display: flex;
  gap: 10px;
}

.reply-body {
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.user {
  /* TODO fix text overflow for when no spaces added*/
  background: grey;
  padding: 8px;
  border-radius: 20px;
  /*TODO max variable based on content*/
  width: 100%;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.like-comment,
.reply_comment {
  cursor: pointer;
}

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- CSS only -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
  <link href="/static/css/style.css" rel="stylesheet">
  <script src="https://js.stripe.com/v3/"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>

<body>

  <div class="post">
    <script id="counter40">
      1
    </script>
    <div class="post_padding">
      <div class="post_top">
        <div class="profile-name">
          <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
          <div>
            <div id="post_top"> jon </div>
            <div id="post_top2" class="location-time"><span class="time">in 3 hours</span><i class="fas fa-globe-americas"></i></div>
          </div>
        </div>
        <div id="three-dots" style="display: block" class="hover">
          <div class="dropdown">
            <div href="#" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></div>
            <div class="dropdown-menu">
              <div id="post_edit_modal" style="display: block" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_edit_modal(40)">
                <i class="bi bi-pencil-square"> Edit</i>
              </div>

              <div id="post_ban_modal" style="display: block" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_ban_modal(1)">
                <i class="bi bi-eye-slash"> Ban</i>
              </div>
              <div id="post_history_modal" style="display: none;" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_history_modal(1)">
                <i class="bi bi-clock-history"> History</i>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!--this is really the post-->
      <div class="media ">
        <div class="text-break" id="post_body">hi</div>
        <img id="media_graphic">
      </div>

      <!--Finish this, need media link, media article-->

      <div class="like-and-comment">
        <div class="d-flex align-items-center">
          <i id="upvote40" class="fas fa-arrow-up hover" style="color: gray;" onclick="vote(40,1)"></i>
          <span id="upvote_count_badge40" class="badge bg-secondary">0</span>
          <i id="downvote40" class="fas fa-arrow-down hover" style="color: gray;" onclick="vote(40,0)"></i>
        </div>

        <div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_award_modal(40)">
          <i class="fas fa-award hover"></i>
        </div>

        <div class="dropdown hover">
          <div class="dropdown-toggle" data-bs-toggle="dropdown"><i class="fas fa-share"></i></div>
          <ul class="dropdown-menu">
            <p id="post_crosspost_modal" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_crosspost_modal(40)">
              <i class="bi bi-signpost-2"> Cross Post</i>
            </p>
            <p id="copytoclipboard" class="dropdown-item" onclick="copyToClipboard('http://127.0.0.1:5000/post/40')">
              <i class="bi bi-clipboard"> Copy Link</i>
            </p>
            <p id="save_post" class="dropdown-item" onclick="save_post(40)">
              <i id="save_post_icon40" class="bi bi-save"> Save</i>
            </p>
          </ul>
        </div>
      </div>

      <div class="view-more">
        <div class="hover" id="load_replies40" onclick="loadReplies(40,0)"></div>
        <div class="hover" id="comment_collapse"> 1 comments</div>
      </div>

      <div class="comment">
        <div id="reply_loader40">
          <!--Append Replies Here-->
          <div class="lk">
            <script id="counter46">
              0
            </script>
            <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
            <div style="width: 100%;">
              <div class="user">
                <div class="reply_author">jon in 6 hours </div>
                <div class="reply-body">word-wrap : break-word; overflow-wrap: break-word;word-wrap : break-word; overflow-wrap: break-word;word-wrap : break-word; overflow-wrap: break-word;word-wrap : break-word; overflow-wrap: break-word;</div>
              </div>
              <div class="reply">
                <div class="d-flex align-items-center">
                  <i id="upvote46" class="fas fa-arrow-up hover" style="color: gray" onclick="vote(46,1)"></i>
                  <span id="upvote_count_badge46" class="badge bg-secondary">0</span>
                  <i id="downvote46" class="fas fa-arrow-down hover" style="color: gray" onclick="vote(46,0)"></i>
                </div>
                <div class="reply_comment" id="reply46">Reply</div>
                <div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_award_modal(46)">
                  <i class="fas fa-award hover"></i>
                </div>
              </div>

              <form id="submit_reply46" style="display: none;" autocomplete="off">
                <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
                <input class="comment_input" id="comment_input46" maxlength="1024" name="body" placeholder="Write a comment3" required="" type="text" value="">
                <div id="comment_input_error46" class="invalid-feedback"></div>
              </form>
              <div id="reply_loader46">
                <!--Nested Replies go here-->
              </div>
            </div>
          </div>
        </div>

        <form id="submit_reply" autocomplete="off">
          <div class="post_comment">
            <img class="profile_image" src="https://robohash.org/006cb570acdab0e0bfc8e3dcb7bb4edf?size=50x50">
            <input class="comment_input" id="comment_input40" maxlength="1024" name="body" placeholder="Write a comment" required="" type="text" value="">
            <div id="comment_input_error40" class="invalid-feedback"></div>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

</body>


问:
How to make mocha fail when no expect within it()
Is there an option to set mocha to report test as failing in case no expect provided within it() function?

Idea is workflow to be like this:

add one it() with desc and callback function

the it() is reported as fail since no expectation is set in the callback

expectation is added

the it() is still reported as fail as expectation is not met since no implementation

implementation is added

the it() is reported as success

refactor

So main intention is while doing canonical TDD style developing newly added test are reported as failed until expectation is set (or test set as pending without callback or skip()), which is again reported as fail and once implementation is done it is reported as success.

Value I see for it() succeeding without expectation is that once it is added it's failure now proves that it is actually working and proves it is failing. Was it intention or am I missing something?

Also, if anyone have idea how to set that up in karma.conf.js would be great.

Thanks

答:
Mocha 9.1 add the --fail-zero option which makes mocha exit with an error code ("non-zero exit code") if no tests are encountered.

Not sure if this is 100% what you're looking for but it's what I was looking for when I came across this Q&A.
This might not work when there are some tests defined but not on a per-it() block. I haven't tested.


问:
C++ unordered_set insert accepts constructor parameters?
Given these two classes

```<code>class User {
    string name;
    string eMail;
    pair<string, string> titleReading;
    vector<pair<string, string> > titlesRead;
}
class UserRecord {
    User* userPtr;
public:
    UserRecord(User* user);
    string getName() const;
    string getEMail() const;
    void setEMail(string eMail);
};
</code>```

And this class which contains an unordered_set of UserRecords

```<code>struct userRecordHash
{
    int operator() (const UserRecord& ur) const
    {
        hash<string> h;
        return h(ur.getEMail());
    }

    bool operator() (const UserRecord& ur1, const UserRecord& ur2) const
    {
        return ur1.getEMail()==ur2.getEMail();
    }
};

typedef tr1::unordered_set<UserRecord, userRecordHash, userRecordHash> HashTabUserRecord;

class ReadingClub {
    vector<Book*> books;
    BST<BookCatalogItem> catalogItems;
    HashTabUserRecord userRecords;
    priority_queue<User> readerCandidates;
};
</code>```

Why am I able to do unordered_set.insert(User*)? Does it call the UserRecord constructor?

答:
Your UserRecord::UserRecord(User*) constructor is a converting constructor, which means that it implicitly converts a User* value into a UserRecord object.

If you wish to prohibit this you can mark the constructor as explicit such that no automatic conversion is ever performed implicitly. You will always have to explicitly call the constructor you want to use.

This has nothing to with std::unordered_set. Observe:

```<code>struct I { I(int) {} };
struct E { explicit E(int) {} };
int main(){
  I a = 0; // okay
  E b = 0; // not okay
  E c(0); // okay
  E d = E(0); // okay
}
</code>```

Note that with an explicit constructor, you could still std::unordered_set::emplace values (as opposed to insert). Or you could explicitly create the object you want to insert.

Body:
Given these two classes

class User {
    string name;
    string eMail;
    pair<string, string> titleReading;
    vector<pair<string, string> > titlesRead;
}
class UserRecord {
    User* userPtr;
public:
    UserRecord(User* user);
    string getName() const;
    string getEMail() const;
    void setEMail(string eMail);
};

And this class which contains an unordered_set of UserRecords

struct userRecordHash
{
    int operator() (const UserRecord& ur) const
    {
        hash<string> h;
        return h(ur.getEMail());
    }

    bool operator() (const UserRecord& ur1, const UserRecord& ur2) const
    {
        return ur1.getEMail()==ur2.getEMail();
    }
};

typedef tr1::unordered_set<UserRecord, userRecordHash, userRecordHash> HashTabUserRecord;

class ReadingClub {
    vector<Book*> books;
    BST<BookCatalogItem> catalogItems;
    HashTabUserRecord userRecords;
    priority_queue<User> readerCandidates;
};

Why am I able to do unordered_set.insert(User*)? Does it call the UserRecord constructor?

Body:
Your UserRecord::UserRecord(User*) constructor is a converting constructor, which means that it implicitly converts a User* value into a UserRecord object.

If you wish to prohibit this you can mark the constructor as explicit such that no automatic conversion is ever performed implicitly. You will always have to explicitly call the constructor you want to use.

This has nothing to with std::unordered_set. Observe:

struct I { I(int) {} };
struct E { explicit E(int) {} };
int main(){
  I a = 0; // okay
  E b = 0; // not okay
  E c(0); // okay
  E d = E(0); // okay
}

Note that with an explicit constructor, you could still std::unordered_set::emplace values (as opposed to insert). Or you could explicitly create the object you want to insert.


问:
PyAudio error at the time of intallation (subprocess-exited-with-error)
```<code>Building wheel for pyaudio (setup.py) ... error
  error: subprocess-exited-with-error
</code>```

Showing this error at the time of installation, I have updated pip and Python version but still got the same error.
The full error:

```<code>(stt) F:\Python>pip install pyaudio
Collecting pyaudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: pyaudio
  Building wheel for pyaudio (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [53 lines of output]
      running bdist_wheel
      running build
      running build_py
      running build_ext
      building '_portaudio' extension
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "C:\Users\Jug\AppData\Local\Temp\pip-install-7dl19imj\pyaudio_618223816ae04aecb9311a803aa75afe\setup.py", line 106, in <module>
          setup(name='PyAudio',
        File "F:\Python\stt\lib\site-packages\setuptools\__init__.py", line 155, in setup
          return distutils.core.setup(**attrs)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\core.py", line 148, in setup
          return run_commands(dist)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\core.py", line 163, in run_commands
          dist.run_commands()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 967, in run_commands
          self.run_command(cmd)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command
          cmd_obj.run()
        File "F:\Python\stt\lib\site-packages\wheel\bdist_wheel.py", line 299, in run
          self.run_command('build')
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\cmd.py", line 313, in run_command
          self.distribution.run_command(command)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command
          cmd_obj.run()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build.py", line 135, in run
          self.run_command(cmd_name)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\cmd.py", line 313, in run_command
          self.distribution.run_command(command)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command
          cmd_obj.run()
        File "F:\Python\stt\lib\site-packages\setuptools\command\build_ext.py", line 79, in run
          _build_ext.run(self)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 339, in run
          self.build_extensions()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 448, in build_extensions
          self._build_extensions_serial()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 473, in _build_extensions_serial
          self.build_extension(ext)
        File "F:\Python\stt\lib\site-packages\setuptools\command\build_ext.py", line 202, in build_extension
          _build_ext.build_extension(self, ext)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 528, in build_extension
          objects = self.compiler.compile(sources,
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 327, in compile
          self.initialize()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 224, in initialize
          vc_env = _get_vc_env(plat_spec)
        File "F:\Python\stt\lib\site-packages\setuptools\msvc.py", line 316, in msvc14_get_vc_env
          return _msvc14_get_vc_env(plat_spec)
        File "F:\Python\stt\lib\site-packages\setuptools\msvc.py", line 270, in _msvc14_get_vc_env
          raise distutils.errors.DistutilsPlatformError(
      setuptools._distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pyaudio
  Running setup.py clean for pyaudio
Failed to build pyaudio
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
  error: subprocess-exited-with-error

  × Running setup.py install for pyaudio did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      running install
      F:\Python\stt\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      running build_ext
      building '_portaudio' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pyaudio

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
</code>```

答:
Get your appropriate .whl file from https://www.lfd.uci.edu/~gohlke/pythonlibs/ under pyaudio. You can find the appropriate .whl file by typing python in your cmd or terminal. You would get something like this:

```<code>Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
</code>```

Image description:

Note the python version and if python is 64 or 32 bit. Then get the .whl file appropriate for that version and machine. For me it would be this .whl file:

```<code>PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl
</code>```

Next, go to the place where it was downloaded. For example, C:\Users\user\Downloads> then install .whl file using pip. For example in my case:

```<code>pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl
</code>```

or if the above doesn't work try:

Since pyAudio has portAudio as a dependency, you first have to install portaudio.

brew install portaudio

Then try: pip3 install pyAudio. If the problem persists after installing portAudio, you can specify the directory path where the compiler will be able to find the source programs (e.g: portaudio.h). Since the headers should be in the /usr/local/include directory:

```<code>pip install --global-option='build_ext' --global-option='-I/usr/local/include' --global-option='-L/usr/local/lib' pyaudio
</code>```

Body:
Building wheel for pyaudio (setup.py) ... error
  error: subprocess-exited-with-error

Showing this error at the time of installation, I have updated pip and Python version but still got the same error.
The full error:

(stt) F:\Python>pip install pyaudio
Collecting pyaudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: pyaudio
  Building wheel for pyaudio (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [53 lines of output]
      running bdist_wheel
      running build
      running build_py
      running build_ext
      building '_portaudio' extension
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "C:\Users\Jug\AppData\Local\Temp\pip-install-7dl19imj\pyaudio_618223816ae04aecb9311a803aa75afe\setup.py", line 106, in <module>
          setup(name='PyAudio',
        File "F:\Python\stt\lib\site-packages\setuptools\__init__.py", line 155, in setup
          return distutils.core.setup(**attrs)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\core.py", line 148, in setup
          return run_commands(dist)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\core.py", line 163, in run_commands
          dist.run_commands()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 967, in run_commands
          self.run_command(cmd)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command
          cmd_obj.run()
        File "F:\Python\stt\lib\site-packages\wheel\bdist_wheel.py", line 299, in run
          self.run_command('build')
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\cmd.py", line 313, in run_command
          self.distribution.run_command(command)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command
          cmd_obj.run()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build.py", line 135, in run
          self.run_command(cmd_name)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\cmd.py", line 313, in run_command
          self.distribution.run_command(command)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command
          cmd_obj.run()
        File "F:\Python\stt\lib\site-packages\setuptools\command\build_ext.py", line 79, in run
          _build_ext.run(self)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 339, in run
          self.build_extensions()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 448, in build_extensions
          self._build_extensions_serial()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 473, in _build_extensions_serial
          self.build_extension(ext)
        File "F:\Python\stt\lib\site-packages\setuptools\command\build_ext.py", line 202, in build_extension
          _build_ext.build_extension(self, ext)
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\command\build_ext.py", line 528, in build_extension
          objects = self.compiler.compile(sources,
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 327, in compile
          self.initialize()
        File "F:\Python\stt\lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 224, in initialize
          vc_env = _get_vc_env(plat_spec)
        File "F:\Python\stt\lib\site-packages\setuptools\msvc.py", line 316, in msvc14_get_vc_env
          return _msvc14_get_vc_env(plat_spec)
        File "F:\Python\stt\lib\site-packages\setuptools\msvc.py", line 270, in _msvc14_get_vc_env
          raise distutils.errors.DistutilsPlatformError(
      setuptools._distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pyaudio
  Running setup.py clean for pyaudio
Failed to build pyaudio
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
  error: subprocess-exited-with-error

  × Running setup.py install for pyaudio did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      running install
      F:\Python\stt\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      running build_ext
      building '_portaudio' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pyaudio

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

Body:
Get your appropriate .whl file from https://www.lfd.uci.edu/~gohlke/pythonlibs/ under pyaudio. You can find the appropriate .whl file by typing python in your cmd or terminal. You would get something like this:

Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

Image description:

Note the python version and if python is 64 or 32 bit. Then get the .whl file appropriate for that version and machine. For me it would be this .whl file:

PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl

Next, go to the place where it was downloaded. For example, C:\Users\user\Downloads> then install .whl file using pip. For example in my case:

pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl

or if the above doesn't work try:

Since pyAudio has portAudio as a dependency, you first have to install portaudio.

brew install portaudio

Then try: pip3 install pyAudio. If the problem persists after installing portAudio, you can specify the directory path where the compiler will be able to find the source programs (e.g: portaudio.h). Since the headers should be in the /usr/local/include directory:

pip install --global-option='build_ext' --global-option='-I/usr/local/include' --global-option='-L/usr/local/lib' pyaudio


问:
Converting T-Bill weekly data to a Monthly level data
I want to convert my weekly T bill data to a monthly level

Here is a sample of my Data:

```<code>0   1986-Jan    7.04
1   1986-01-10  7.13
2   1986-01-17  7.17
3   1986-01-24  6.99
4   1986-01-31  6.98
</code>```

I want to get the average of the data at a month level.

For the above example, the out should be:

```<code>0   1986 Jan  7.062
</code>```

Here is what I am trying to do:

```<code>three_month_t_bill_df['Month_Number'] = three_month_t_bill_df['observation_date'].dt.month
three_month_t_bill_df['Year'] = three_month_t_bill_df['observation_date'].dt.year

df2 = three_month_t_bill_df.groupby(['Year','Month_Number']).agg("mean")

</code>```

I am getting the following output:

```<code>1986    1   7.0620
        2   7.0650
        3   6.5650
        4   6.0625
...
1987    1   5.4640
        2   5.5925
        3   5.5875
</code>```

Can someone help in getting the year in all rows and month name instead of month number?

答:
Part 1.

You can use import calendar / df = df['Month_number'].apply( lambda k: calendar.month_name[k]) to get the month names.

Part 2.

The data is all in there, but groupby returns a special DataFrameGroupBy object that doesn't display the grouped data.  You can convert that to a normal data frame using df2 = df2.to_frame().

Body:
I want to convert my weekly T bill data to a monthly level

Here is a sample of my Data:

0   1986-Jan    7.04
1   1986-01-10  7.13
2   1986-01-17  7.17
3   1986-01-24  6.99
4   1986-01-31  6.98

I want to get the average of the data at a month level.

For the above example, the out should be:

0   1986 Jan  7.062

Here is what I am trying to do:

three_month_t_bill_df['Month_Number'] = three_month_t_bill_df['observation_date'].dt.month
three_month_t_bill_df['Year'] = three_month_t_bill_df['observation_date'].dt.year

df2 = three_month_t_bill_df.groupby(['Year','Month_Number']).agg("mean")

I am getting the following output:

1986    1   7.0620
        2   7.0650
        3   6.5650
        4   6.0625
...
1987    1   5.4640
        2   5.5925
        3   5.5875

Can someone help in getting the year in all rows and month name instead of month number?


答:
Suppose your date column is called Date and your dataframe is df and your values is called Value, so you could do:

```<code># Creating a new column to store the new format
df["DateMonth"] = pd.to_datetime(df["Date"]).dt.strftime('%Y %b')
# Group by Value column and get the average
df.groupby(['DateMonth'])['Value'].mean()
</code>```

With that, my output is:

```<code>DateMonth
1986 Jan    7.062
Name: Value, dtype: float64
</code>```

You could also check Python strftime cheatsheet to check new formats if you want.

Title: Converting T-Bill weekly data to a Monthly level data

Body:
Suppose your date column is called Date and your dataframe is df and your values is called Value, so you could do:

# Creating a new column to store the new format
df["DateMonth"] = pd.to_datetime(df["Date"]).dt.strftime('%Y %b')
# Group by Value column and get the average
df.groupby(['DateMonth'])['Value'].mean()

With that, my output is:

DateMonth
1986 Jan    7.062
Name: Value, dtype: float64

You could also check Python strftime cheatsheet to check new formats if you want.


问:
Do we still need Richter's AsyncEnumerator?
Recently I stumbled across the AsyncEnumerator class form Jeffrey Richter's Power Threading Library which seems to solve several problems I'm usually encountering when programming asynchronous stuff.

The idea for this class has been around for quite a while now and I'm wondering if current versions of .NET / C# have built-in support for this mechanism by now or if it is still necessary to rely on a third party library? Or maybe newer versions of .NET have some alternative approach which simplifies asynchronous programming as much as Richter's AsyncEnumerator does?

Or in other words: Is there a reason to not start using Richter's AsyncEnumerator today?

Edit:

Some links with information on AsyncEnumerator:

Jeffrey Richter and his AsyncEnumerator

Simplified APM With The AsyncEnumerator

More AsyncEnumerator Features

答:
An obvious parallel here is PLINQ, but Richter himself dismisses this:

Jeffrey Richter Dec 04, 2008 at 2:27 PMquotereply They are very
  different. Parallel.For in particular is about performing a bunch of
  compute-bound operations in parallel scaling out across all the CPUs
  in teh machine. My AsyncEnumerator is mostly about issuing one or more
  concurrent I/O-bound operations without have any threads block for
  them to complete.

However, the C# async CTP may be useful here, making thread continuations much more reasonable, i.e.

```<code>var bytesRead = await stream.ReadAsync(...);
Console.WriteLine(bytesRead); // woah! we're on a different thread now!
</code>```

Here, the C# compiler re-writes everything around await instuctions, such that it becomes a callback/continuation to the existing async operation (which must return an "awaitable" value). Once this is in production, I hope this will become a much more natural way to write code with intrinsic delays due to async.

Body:
An obvious parallel here is PLINQ, but Richter himself dismisses this:

Jeffrey Richter Dec 04, 2008 at 2:27 PMquotereply They are very
  different. Parallel.For in particular is about performing a bunch of
  compute-bound operations in parallel scaling out across all the CPUs
  in teh machine. My AsyncEnumerator is mostly about issuing one or more
  concurrent I/O-bound operations without have any threads block for
  them to complete.

However, the C# async CTP may be useful here, making thread continuations much more reasonable, i.e.

var bytesRead = await stream.ReadAsync(...);
Console.WriteLine(bytesRead); // woah! we're on a different thread now!

Here, the C# compiler re-writes everything around await instuctions, such that it becomes a callback/continuation to the existing async operation (which must return an "awaitable" value). Once this is in production, I hope this will become a much more natural way to write code with intrinsic delays due to async.


问:
method.invoke dynamic exception throwing
short Summary : I want to create a wrapper/Interceptor for our java clients making external call and we have a lot of different java clients so I don't want to map exception one by one.

```<code>            public Object handleRequest(Object delegate, Method method, Object[] objects) {
                Object result = null;
                try {
                    result = method.invoke(delegate, objects);
                    // do some logic
                } catch ( IllegalAccessException | IllegalArgumentException e) {
                    // do nothing
                } catch (InvocationTargetException e) {
                    throw e.getCause(); //java: unreported exception java.lang.Throwable; must be caught or declared to be thrown
                }
                return result;
            };
        };
    }

</code>```

In the code above, what I would like to do is throw the exception that the delegate is throwing (which would be obtainable by getting e.getCause(), but it is throwable). Since we have many maaany clients, I want to avoid checking it with many if and else statements and checking with isInstanceOf() (or other variations of it). Is there a way for me to throw the whatever e.getCause() as type of that specific type programatically?

答:
No.  If you are handed an arbitrary Method, you can't make the caller know what particular type of exception that method throws.  You can of course throw Throwable and just throw e.getCause(), but it sounds like that's what you don't want to do -- but there's no way around it given the rest of your design.

You could move away from reflection and use interfaces and method references, but it's not clear from the context how feasible that is.

Body:
short Summary : I want to create a wrapper/Interceptor for our java clients making external call and we have a lot of different java clients so I don't want to map exception one by one.

            public Object handleRequest(Object delegate, Method method, Object[] objects) {
                Object result = null;
                try {
                    result = method.invoke(delegate, objects);
                    // do some logic
                } catch ( IllegalAccessException | IllegalArgumentException e) {
                    // do nothing
                } catch (InvocationTargetException e) {
                    throw e.getCause(); //java: unreported exception java.lang.Throwable; must be caught or declared to be thrown
                }
                return result;
            };
        };
    }

In the code above, what I would like to do is throw the exception that the delegate is throwing (which would be obtainable by getting e.getCause(), but it is throwable). Since we have many maaany clients, I want to avoid checking it with many if and else statements and checking with isInstanceOf() (or other variations of it). Is there a way for me to throw the whatever e.getCause() as type of that specific type programatically?