问:
Remove the brackets in json?
How can I get rid of the brackets below for json processing?

```<code>[{"success":true,"filename":"bialding_and_rebialding_plymouth02.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth03.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth04.jpg"}]
</code>```

The result above is processed by the class below into an array,

```<code>function handle_upload($upload_directory)
    {
        # Loop the code according to the number of files.
        for($i = 1; $i <= $this->total; $i++)
        {
            ...

            if ($this->file->save($upload_directory.$name_filtered.'.'.$file_extension , $i-1))
            {
                $message[] = array('success'=>true,'filename'=>$name_filtered.'.'.$file_extension);
            }
            else
            {
                $message[] = array('error'=> 'Could not save uploaded file.' . 'The upload was cancelled, or server error encountered');
            }
        }

        return $message;
    }
</code>```

Then I use json_encode to turn the array into json format,

```<code>$uploader = new uploader();
$result = $uploader->handle_upload('uploads/');

echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
</code>```

But I only need this in my result without the brackets,

```<code>{"success":true,"filename":"bialding_and_rebialding_plymouth02.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth03.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth04.jpg"}
</code>```

答: str_replace(array('[', ']'), '', htmlspecialchars(json_encode($result), ENT_NOQUOTES)); ?

Title: Remove the brackets in json?

Body:
How can I get rid of the brackets below for json processing?

[{"success":true,"filename":"bialding_and_rebialding_plymouth02.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth03.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth04.jpg"}]

The result above is processed by the class below into an array,

function handle_upload($upload_directory)
    {
        # Loop the code according to the number of files.
        for($i = 1; $i <= $this->total; $i++)
        {
            ...

            if ($this->file->save($upload_directory.$name_filtered.'.'.$file_extension , $i-1))
            {
                $message[] = array('success'=>true,'filename'=>$name_filtered.'.'.$file_extension);
            }
            else
            {
                $message[] = array('error'=> 'Could not save uploaded file.' . 'The upload was cancelled, or server error encountered');
            }
        }

        return $message;
    }

Then I use json_encode to turn the array into json format,

$uploader = new uploader();
$result = $uploader->handle_upload('uploads/');

echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);

But I only need this in my result without the brackets,

{"success":true,"filename":"bialding_and_rebialding_plymouth02.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth03.jpg"},{"success":true,"filename":"bialding_and_rebialding_plymouth04.jpg"}


来源: stackexchange

问:
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
I tried to find the solution for the below problem, but none of them worked for me. I am developing Angular + Spring Boot application using MySQL + flyway. Please guide whats going wrong here.

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.boot.App.main(App.java:9) [classes/:na]
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.flywaydb.core.Flyway.doValidate(Flyway.java:1108) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.access$300(Flyway.java:62) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1012) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 18 common frames omitted
</code>```

application.properties

```<code>logging.level.org.springframework.web=DEBUG

server.port=8080

spring.h2.console.enabled=true
spring.h2.console.path=/h2

## For H2 DB
#spring.datasource.url=jdbc:h2:file:~/dasboot
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driver-class-name=org.h2.Driver

## For MYSQL DB
spring.datasource.url=jdbc:mysql://localhost:3306/dasboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1

flyway.baseline-on-migrate=true
spring.jpa.hibernate.ddl-auto=false;

#datasource.flyway.url=jdbc:h2:file:~/dasboot
#datasource.flyway.username=sa
#datasource.flyway.password=
#datasource.flyway.driver-class-name=org.h2.Driver

datasource.flyway.url=jdbc:mysql://localhost:3306/dasboot
datasource.flyway.username=root
datasource.flyway.password=root
datasource.flyway.driver-class-name=com.mysql.jdbc.Driver
</code>```

pom.xml

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <name>das-boot</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</code>```

V2__create_shipwreck.sql

```<code>-- For H2 DB
--CREATE TABLE SHIPWRECK(
--  ID INT AUTO_INCREMENT,
--  NAME VARCHAR(255),
--  DESCRIPTION VARCHAR(2000),
--  CONDITION VARCHAR(255),
--  DEPTH INT,
--  LATITUDE DOUBLE,
--  LONGITUDE DOUBLE,
--  YEAR_DISCOVERED INT
--);

CREATE TABLE `dasboot`.`shipwreck` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(255) NULL,
  `DESCRIPTION` VARCHAR(2000) NULL,
  `CONDITION` VARCHAR(255) NULL,
  `DEPTH` INT NULL,
  `LATITUDE` DOUBLE NULL,
  `LONGITUDE` DOUBLE NULL,
  `YEAR_DISCOVERED` INT NULL,
  PRIMARY KEY (`ID`));
</code>```

答:
After your .sql applied to DB, you edited the .sql, flyway may show this error.

If using Postgresql, a quick solution

After dropping tables "flyway_schema_histrory" and the table my .sql created, the error disappeared.
delete table

ContentLicense: CC BY-SA 3.0

Body:
I tried to find the solution for the below problem, but none of them worked for me. I am developing Angular + Spring Boot application using MySQL + flyway. Please guide whats going wrong here.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.boot.App.main(App.java:9) [classes/:na]
Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2
-> Applied to database : 1499248173
-> Resolved locally    : -1729781252
    at org.flywaydb.core.Flyway.doValidate(Flyway.java:1108) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.access$300(Flyway.java:62) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1012) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:1418) ~[flyway-core-3.2.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1006) ~[flyway-core-3.2.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66) ~[spring-boot-autoconfigure-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 18 common frames omitted

application.properties

logging.level.org.springframework.web=DEBUG

server.port=8080

spring.h2.console.enabled=true
spring.h2.console.path=/h2

## For H2 DB
#spring.datasource.url=jdbc:h2:file:~/dasboot
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driver-class-name=org.h2.Driver

## For MYSQL DB
spring.datasource.url=jdbc:mysql://localhost:3306/dasboot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.max-wait=10000
spring.datasource.min-evictable-idle-time-millis=1000
spring.datasource.min-idle=8
spring.datasource.time-between-eviction-runs-millis=1

flyway.baseline-on-migrate=true
spring.jpa.hibernate.ddl-auto=false;

#datasource.flyway.url=jdbc:h2:file:~/dasboot
#datasource.flyway.username=sa
#datasource.flyway.password=
#datasource.flyway.driver-class-name=org.h2.Driver

datasource.flyway.url=jdbc:mysql://localhost:3306/dasboot
datasource.flyway.username=root
datasource.flyway.password=root
datasource.flyway.driver-class-name=com.mysql.jdbc.Driver

pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <name>das-boot</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

V2__create_shipwreck.sql

-- For H2 DB
--CREATE TABLE SHIPWRECK(
--  ID INT AUTO_INCREMENT,
--  NAME VARCHAR(255),
--  DESCRIPTION VARCHAR(2000),
--  CONDITION VARCHAR(255),
--  DEPTH INT,
--  LATITUDE DOUBLE,
--  LONGITUDE DOUBLE,
--  YEAR_DISCOVERED INT
--);

CREATE TABLE `dasboot`.`shipwreck` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(255) NULL,
  `DESCRIPTION` VARCHAR(2000) NULL,
  `CONDITION` VARCHAR(255) NULL,
  `DEPTH` INT NULL,
  `LATITUDE` DOUBLE NULL,
  `LONGITUDE` DOUBLE NULL,
  `YEAR_DISCOVERED` INT NULL,
  PRIMARY KEY (`ID`));

ContentLicense: CC BY-SA 4.0


问:
Laravel 8 variable value from aggregate sum of multiple column values
I need to create a variable thats the aggregate sum of multiple values.  I have about 25 values to to add together--below is a small snippet.  The below works, but stringing all the values together with a + seems a bit dirty.  Is there another way?

```<code>// Calculate Modification Points
        $trackPTS = $this->track ? 20 : 0;
        $shockTowerPTS = $this->shock_tower ? 10 : 0;
        $loweringPTS = $this->lowering ? 10 : 0;
        $camberPTS = $this->camber ? 20 : 0;
        $monoballPTS = $this->monoball ? 10 : 0;
        $tubeFramePTS = $this->tube_frame ? 100 : 0;
        $pasmPTS = $this->pasm ? 20 : 0;
        $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;

        $totalModificationPoints = $treadWearPoints + $trackPTS + $shockTowerPTS + $loweringPTS + $camberPTS + $monoballPTS + $tubeFramePTS + $pasmPTS + $rearAxleSteerPTS;
</code>```

答:
I would put all possible class variable names to an array and then i would iterate it. Like that:

<?php
class Calc {

  private $track = 30;
  private $shock_tower = 40;
  private $lowering = 10;

  public function __construct() {
    $keyValues = [
        ['track', 20],
        ['shock_tower', 10],
        ['lowering', 10],
    ];

    $sum = 0;
    foreach($keyValues as $set) {
        $sum += (int) $this->{$set[0]} ?? $set[1];
    }

    print_r($sum);
  }
}

new Calc();
```

Body:
I need to create a variable thats the aggregate sum of multiple values.  I have about 25 values to to add together--below is a small snippet.  The below works, but stringing all the values together with a + seems a bit dirty.  Is there another way?

// Calculate Modification Points
        $trackPTS = $this->track ? 20 : 0;
        $shockTowerPTS = $this->shock_tower ? 10 : 0;
        $loweringPTS = $this->lowering ? 10 : 0;
        $camberPTS = $this->camber ? 20 : 0;
        $monoballPTS = $this->monoball ? 10 : 0;
        $tubeFramePTS = $this->tube_frame ? 100 : 0;
        $pasmPTS = $this->pasm ? 20 : 0;
        $rearAxleSteerPTS = $this->rear_axle_steer ? 10 : 0;

        $totalModificationPoints = $treadWearPoints + $trackPTS + $shockTowerPTS + $loweringPTS + $camberPTS + $monoballPTS + $tubeFramePTS + $pasmPTS + $rearAxleSteerPTS;


问:
PostgreSQL - Delete last item of JSONB array
I have a field that holds JSONB arrays. How can I delete the last item?</p>
```<code>[
  {
    "name": "test1",
  },
  {
    "name": "test2",
  },
]
</code>```

答:
You can use jsonb_column - (-1). See the documentation.

```<code>WITH data(j) AS (
    VALUES ('[
      {
        "name": "test1"
      },
      {
        "name": "test2"
      },
      {
        "name": "test3"
      }
    ]'::JSONB)
)
SELECT j, j - (-1) AS all_but_last, j - 1 AS without_second_element
FROM data;
</code>```

j
all_but_last
without_second_element

[{"name":"test1"},{"name":"test2"},{"name":"test3"}]
[{"name":"test1"},{"name":"test2"}]
[{"name":"test1"},{"name":"test3"}]

View on DB Fiddle

Body:
I have a field that holds JSONB arrays. How can I delete the last item?

[
  {
    "name": "test1",
  },
  {
    "name": "test2",
  },
]

Body:
You can use jsonb_column - (-1). See the documentation.

WITH data(j) AS (
    VALUES ('[
      {
        "name": "test1"
      },
      {
        "name": "test2"
      },
      {
        "name": "test3"
      }
    ]'::JSONB)
)
SELECT j, j - (-1) AS all_but_last, j - 1 AS without_second_element
FROM data;

j
all_but_last
without_second_element

[{"name":"test1"},{"name":"test2"},{"name":"test3"}]
[{"name":"test1"},{"name":"test2"}]
[{"name":"test1"},{"name":"test3"}]

View on DB Fiddle


问:
How to execute Nested loop in Django Template on single Queryset
I want to render my query set data on template with a slider. Each slider will contain 3 product query like this

But I am unable to to this dynamically with for loop in Django template language. My Template code is

Latest Products

                            {% for product in recent_products %}

{{product.name}}

                                            {{product.price}} Tk

                            {% endfor %}

```
</div>
</div>
</p>
<p>here is my view function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>def index(request):
    products = Product.objects.all()
    categorys = ProductCategory.objects.all()

    today = timezone.now().date()
    last_day = today - timezone.timedelta(days=7)

    today = datetime.strftime(today, "%Y-%m-%d")
    last_day = datetime.strftime(last_day, "%Y-%m-%d")

    print(last_day)
    recent_products = Product.objects.filter(added_time__range=[last_day, today]).order_by("-added_time")
    context = {
        'products': products,
        'categorys': categorys,
        'recent_products': recent_products
    }
    return render(request, 'index.html', context)</code>```

and my model class is:

class ProductCategory(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(blank=True, null=True)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField(blank=True, null=True)
    ratings = models.FloatField(blank=True, null=True)
    number_of_ratings = models.IntegerField(blank=True, null=True)
    images = models.ImageField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    # user_review need to be added
    discount_rate = models.IntegerField(default=0)
    available_stock = models.IntegerField(default=0)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True)

    @property
    def discount(self):
        if self.discount_rate > 0:
            discounted_price = self.price - self.price * self.discount_rate / 100
            return discounted_price```

答:
In your views.py, change

today = timezone.now().date() into

today = timezone.now()

Body:
I want to render my query set data on template with a slider. Each slider will contain 3 product query like this

But I am unable to to this dynamically with for loop in Django template language. My Template code is

Latest Products

                            {% for product in recent_products %}

{{product.name}}

                                            {{product.price}} Tk

                            {% endfor %}

here is my view function:

def index(request):
    products = Product.objects.all()
    categorys = ProductCategory.objects.all()

    today = timezone.now().date()
    last_day = today - timezone.timedelta(days=7)

    today = datetime.strftime(today, "%Y-%m-%d")
    last_day = datetime.strftime(last_day, "%Y-%m-%d")

    print(last_day)
    recent_products = Product.objects.filter(added_time__range=[last_day, today]).order_by("-added_time")
    context = {
        'products': products,
        'categorys': categorys,
        'recent_products': recent_products
    }
    return render(request, 'index.html', context)

and my model class is:

class ProductCategory(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(blank=True, null=True)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField(blank=True, null=True)
    ratings = models.FloatField(blank=True, null=True)
    number_of_ratings = models.IntegerField(blank=True, null=True)
    images = models.ImageField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    # user_review need to be added
    discount_rate = models.IntegerField(default=0)
    available_stock = models.IntegerField(default=0)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True)

    @property
    def discount(self):
        if self.discount_rate > 0:
            discounted_price = self.price - self.price * self.discount_rate / 100
            return discounted_price


问:
Flutter Local Notifications runs the Callback function on every hot restart
I am currently working on a Habit Tracker app in Flutter. I want to send a notification to the user at 11PM everyday mentioning the number of Habits they have left for the day, if there is any

My Problem: The callback function runs every time I hot restart the app, or in cases where the device is not connected, it runs every time I close the app and open it again. This happens until the end of the day (12:00 AM). What is the fix to this? How do I make it send the notification only once a day. This feels like a simple fix but I'm not sure what I'm doing wrong.

My Code:

```<code>final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

void scheduleNotification() async
{
  print("scheduleNotification() function Ran");
  var scheduledNotificationDateTime = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 23, 00, 00);

  var androidPlatformChannelSpecifics = AndroidNotificationDetails(
    'habit_notif',
    'habit_notif',
    channelDescription: 'Channel for Habit notification',
    icon: 'applogocircle2',
    largeIcon: DrawableResourceAndroidBitmap('applogoyellowsquare'),
  );

  var iOSPlatformChannelSpecifics = IOSNotificationDetails(
      presentAlert: true,
      presentBadge: true,
      presentSound: true
  );
  var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics
  );

  List<Map<String, dynamic>> queryRows = await DatabaseHelper.instance.queryAllValues();

  int completed = queryRows[0]["todayCompleted"];
  int total = queryRows[0]["todayTotal"];

  if(completed != total)
  {
    await flutterLocalNotificationsPlugin.schedule(
      0,
      'You haven\'t completed all your habits for today!',
      "You have ${total-completed} habits left",
      scheduledNotificationDateTime,
      platformChannelSpecifics,
      androidAllowWhileIdle: true,
    );
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await UserSimplePreferences.init();
  runApp(const MyApp());

  WidgetsFlutterBinding.ensureInitialized();

  var initializationSettingsAndroid = AndroidInitializationSettings('applogo');
  var initializationSettingsIOS = IOSInitializationSettings(
    requestAlertPermission: true,
    requestBadgePermission: true,
    requestSoundPermission: true,
    onDidReceiveLocalNotification: (int id, String? title, String? body, String? payload) async {}
  );

  var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS
  );

  await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onSelectNotification: (String? payload) async {
        if (payload != null) {
          debugPrint('Notification payload: ' + payload);
        }
      }
  );

  scheduleNotification();
  );
}
</code>```

答:
@Zuhaib
First of all, my answer is about to be theoretical because I don't see your project, but I hope you understand, I am sharing a simple yet effective technique while working with notifying users, forgetting username/password, etc.

Let me explain what I have done while working in a situation like this, first of all in the table (you might use a database to store user data), here I will add a column for a user table let's call it "isNotified" int data type and "notifiedAt" which is a DateTime data type, nextNotifiedAt which is a DateTime data type as well, this one stores the next 24H value, something like this:

```<code>before:
isNotified = 0
notifiedAt = null
nextNotifiedAt = null

after notified:
isNotified = 1
notifiedAt = 2/12/2022 11:00PM
nextNotifiedAt = 3/12/2022 11:00PM
</code>```

Now, when users need to be notified, you will get the user's info from the database, username and how many tasks he/she needs to do... here at:

```<code>List<Map<String, dynamic>> queryRows = await DatabaseHelper.instance.queryAllValues();

int completed = queryRows[0]["todayCompleted"];
int total = queryRows[0]["todayTotal"]
</code>```

you have to retrieve those 3 columns you also get "isNotified" and "notifiedAt"
for user "Awat" => isNotified = 0 and notifiedAt = NULL meaning I am not notified yet,
when you send me a notification for the first time at:

```<code>  if(completed != total){
    .....
    // IS it my first time you notifiy me?
    if (isNotified == 0){
     DO UPDATE isNotified = 1 and notifiedAt = CURRENT DATETIME (in mysql use getdate());
     // update tbl_user set isNotified = 1, notifiedAt = getdate() where user_id = X
    }else{
     // at anytime you have notified me, this is a new day..
     if (notifiedAt > nextNotifiedAt){
       // DO UPDATE
     }

    }

  }
</code>```

by doing this you send only 1 time, also you can store when you have notified the user to do the task...

don't use local datetime here at:

```<code>  var scheduledNotificationDateTime = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 23, 00, 00);
</code>```

as you know users can change their DateTime manually, so get DateTime from the server (your database server), and then make the difference between current users DateTime and your database server's DateTime

```<code>var dbDateTime = getDateTimeFromServer()
var localDateTime = DateTime(...)
</code>```

if the user changed the date and time from his/her cellphone you have both values stored in a database no one can access those, notifiedAt = 2/12/2022 11:00 PM
nextNotifiedAt = 3/12/2022 11:00 PM

hope you refactor your code and implement this, also I do apologize most of it is theory.

Body:
I am currently working on a Habit Tracker app in Flutter. I want to send a notification to the user at 11PM everyday mentioning the number of Habits they have left for the day, if there is any

My Problem: The callback function runs every time I hot restart the app, or in cases where the device is not connected, it runs every time I close the app and open it again. This happens until the end of the day (12:00 AM). What is the fix to this? How do I make it send the notification only once a day. This feels like a simple fix but I'm not sure what I'm doing wrong.

My Code:

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

void scheduleNotification() async
{
  print("scheduleNotification() function Ran");
  var scheduledNotificationDateTime = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 23, 00, 00);

  var androidPlatformChannelSpecifics = AndroidNotificationDetails(
    'habit_notif',
    'habit_notif',
    channelDescription: 'Channel for Habit notification',
    icon: 'applogocircle2',
    largeIcon: DrawableResourceAndroidBitmap('applogoyellowsquare'),
  );

  var iOSPlatformChannelSpecifics = IOSNotificationDetails(
      presentAlert: true,
      presentBadge: true,
      presentSound: true
  );
  var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics
  );

  List<Map<String, dynamic>> queryRows = await DatabaseHelper.instance.queryAllValues();

  int completed = queryRows[0]["todayCompleted"];
  int total = queryRows[0]["todayTotal"];

  if(completed != total)
  {
    await flutterLocalNotificationsPlugin.schedule(
      0,
      'You haven\'t completed all your habits for today!',
      "You have ${total-completed} habits left",
      scheduledNotificationDateTime,
      platformChannelSpecifics,
      androidAllowWhileIdle: true,
    );
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await UserSimplePreferences.init();
  runApp(const MyApp());

  WidgetsFlutterBinding.ensureInitialized();

  var initializationSettingsAndroid = AndroidInitializationSettings('applogo');
  var initializationSettingsIOS = IOSInitializationSettings(
    requestAlertPermission: true,
    requestBadgePermission: true,
    requestSoundPermission: true,
    onDidReceiveLocalNotification: (int id, String? title, String? body, String? payload) async {}
  );

  var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS
  );

  await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onSelectNotification: (String? payload) async {
        if (payload != null) {
          debugPrint('Notification payload: ' + payload);
        }
      }
  );

  scheduleNotification();
  );
}

Body:
@Zuhaib
First of all, my answer is about to be theoretical because I don't see your project, but I hope you understand, I am sharing a simple yet effective technique while working with notifying users, forgetting username/password, etc.

Let me explain what I have done while working in a situation like this, first of all in the table (you might use a database to store user data), here I will add a column for a user table let's call it "isNotified" int data type and "notifiedAt" which is a DateTime data type, nextNotifiedAt which is a DateTime data type as well, this one stores the next 24H value, something like this:

before:
isNotified = 0
notifiedAt = null
nextNotifiedAt = null

after notified:
isNotified = 1
notifiedAt = 2/12/2022 11:00PM
nextNotifiedAt = 3/12/2022 11:00PM

Now, when users need to be notified, you will get the user's info from the database, username and how many tasks he/she needs to do... here at:

List<Map<String, dynamic>> queryRows = await DatabaseHelper.instance.queryAllValues();

int completed = queryRows[0]["todayCompleted"];
int total = queryRows[0]["todayTotal"]

you have to retrieve those 3 columns you also get "isNotified" and "notifiedAt"
for user "Awat" => isNotified = 0 and notifiedAt = NULL meaning I am not notified yet,
when you send me a notification for the first time at:

  if(completed != total){
    .....
    // IS it my first time you notifiy me?
    if (isNotified == 0){
     DO UPDATE isNotified = 1 and notifiedAt = CURRENT DATETIME (in mysql use getdate());
     // update tbl_user set isNotified = 1, notifiedAt = getdate() where user_id = X
    }else{
     // at anytime you have notified me, this is a new day..
     if (notifiedAt > nextNotifiedAt){
       // DO UPDATE
     }

    }

  }

by doing this you send only 1 time, also you can store when you have notified the user to do the task...

don't use local datetime here at:

  var scheduledNotificationDateTime = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 23, 00, 00);

as you know users can change their DateTime manually, so get DateTime from the server (your database server), and then make the difference between current users DateTime and your database server's DateTime

var dbDateTime = getDateTimeFromServer()
var localDateTime = DateTime(...)

if the user changed the date and time from his/her cellphone you have both values stored in a database no one can access those, notifiedAt = 2/12/2022 11:00 PM
nextNotifiedAt = 3/12/2022 11:00 PM

hope you refactor your code and implement this, also I do apologize most of it is theory.


问:
Getting error duing maven org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile goal
While trying to build a gerrit plugin project, I seem to be seeing this error</p>
```<code>[ERROR] error: Bad service configuration file, or exception thrown while constructing Processor object: javax.annotation.processing.Processor: com.ryanharter.auto.value.gson.factory.AutoValueGsonAdapterFactoryProcessor Unable to get public no-arg constructor
[ERROR]
</code>```

答:
There are not many details to what you're trying to do, but I've found this through a simple google search:

The default maven lifecycle runs javac with javax.annotation.processing.Processor file as a part of classpath. This cause compiler to expect a compiled instance of annotation processors listed in the files. But LogMeCustomAnnotationProcessor is not compiled at that moment so compiler raises "Bad service configuration file ..." error. See bug report.

To solve this issue maven compilation phase can be separated to compile annotation processor at the first place and then compile whole project.

```<code><build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
        <executions>
            <execution>
                <id>default-compile</id>
                <configuration>
                    <compilerArgument>-proc:none</compilerArgument>
                    <includes>
                        <include>fun/n/learn/annotation/LogMeCustomAnnotationProcessor.java</include>
                        <!--include dependencies required for LogMeCustomAnnotationProcessor -->
                    </includes>
                </configuration>
            </execution>
            <execution>
                <id>compile-project</id>
                <phase>compile</phase>
                <goals>
                    <goal>compile</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</code>```

default-compile execution compiles LogMeCustomAnnotationProcessor with disabled annotation processing in order to have successful compilation.
compile-project compiles whole project with annotaton processing.

Body:
While trying to build a gerrit plugin project, I seem to be seeing this error

[ERROR] error: Bad service configuration file, or exception thrown while constructing Processor object: javax.annotation.processing.Processor: com.ryanharter.auto.value.gson.factory.AutoValueGsonAdapterFactoryProcessor Unable to get public no-arg constructor
[ERROR]

Body:
There are not many details to what you're trying to do, but I've found this through a simple google search:

The default maven lifecycle runs javac with javax.annotation.processing.Processor file as a part of classpath. This cause compiler to expect a compiled instance of annotation processors listed in the files. But LogMeCustomAnnotationProcessor is not compiled at that moment so compiler raises "Bad service configuration file ..." error. See bug report.

To solve this issue maven compilation phase can be separated to compile annotation processor at the first place and then compile whole project.

<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
        <executions>
            <execution>
                <id>default-compile</id>
                <configuration>
                    <compilerArgument>-proc:none</compilerArgument>
                    <includes>
                        <include>fun/n/learn/annotation/LogMeCustomAnnotationProcessor.java</include>
                        <!--include dependencies required for LogMeCustomAnnotationProcessor -->
                    </includes>
                </configuration>
            </execution>
            <execution>
                <id>compile-project</id>
                <phase>compile</phase>
                <goals>
                    <goal>compile</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>

default-compile execution compiles LogMeCustomAnnotationProcessor with disabled annotation processing in order to have successful compilation.
compile-project compiles whole project with annotaton processing.


问:
Why can't pip find winrt?
I just bought a new laptop and I'm trying to set it up with python. I am using python 3.10.0, windows 10, pip v21.3. For the most part, pip seems to be working correctly, I've already used it to install multiple packages such as pygame. When I try to install winrt, however, I get this error

```<code>C:\Users\matth>pip install winrt
ERROR: Could not find a version that satisfies the requirement winrt (from versions: none)
ERROR: No matching distribution found for winrt
</code>```

My old laptop is still able to uninstall and reinstall winrt using pip without a problem, and again pip works on my new laptop for other packages, just not winrt. Any idea what the problem is and how I fix it?

答:
Microsoft has not been maintaining the winrt package. There is no binary wheel for Python 3.10 as seen on PyPI. There is also a request for this on GitHub.

I have started a community-maintained fork of the PyWinRT project. You can install and use winsdk instead. It supports Python 3.10. Just replace winrt with winsdk in your imports.

A list of improvements and bug fixes compared to the winrt package can be found in the changelog.

Title: Why can't pip find winrt?

Body:
I just bought a new laptop and I'm trying to set it up with python. I am using python 3.10.0, windows 10, pip v21.3. For the most part, pip seems to be working correctly, I've already used it to install multiple packages such as pygame. When I try to install winrt, however, I get this error

C:\Users\matth>pip install winrt
ERROR: Could not find a version that satisfies the requirement winrt (from versions: none)
ERROR: No matching distribution found for winrt

My old laptop is still able to uninstall and reinstall winrt using pip without a problem, and again pip works on my new laptop for other packages, just not winrt. Any idea what the problem is and how I fix it?


问:
C# For Loop with LIST using LINQ
I'm using LINQ and returning a list to my Business Logic Layer. I'mtrying to change one of the values in the list (changing the 'star' rating to an image with the number of stars).

Although the counter (i) appears to be working, the FOR loop is not working correctly.  The first time through it stops at the correct IF but then it pops out at the ELSE statement for everything and all values end up with "star0.png."  It appears as though I'm not cycling through the list???  Thanks in advance!

```<code>    for (int i = 0; i < ReviewList.Count; i++)
    {
        string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
        if (serviceCode == "*")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star1.png";
        }
        else if (serviceCode == "**")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star2.png";
        }
        else if (serviceCode == "***")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star3.png";
        }
        else if (serviceCode == "****")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star4.png";
        }
        else
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";
        }
    }
</code>```

答:
If you know each item will consist of a number of stars, why not do this?:</p>

```<code>for (int i = 0; i < ReviewList.Count; i++)
{
    string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
    ReviewList[i].SERVICE.SERVICE_DESC = "star" + serviceCode.Length + ".png";
}
</code>```

Title: C# For Loop with LIST using LINQ

Body:
I'm using LINQ and returning a list to my Business Logic Layer. I'mtrying to change one of the values in the list (changing the 'star' rating to an image with the number of stars).

Although the counter (i) appears to be working, the FOR loop is not working correctly.  The first time through it stops at the correct IF but then it pops out at the ELSE statement for everything and all values end up with "star0.png."  It appears as though I'm not cycling through the list???  Thanks in advance!

    for (int i = 0; i < ReviewList.Count; i++)
    {
        string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
        if (serviceCode == "*")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star1.png";
        }
        else if (serviceCode == "**")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star2.png";
        }
        else if (serviceCode == "***")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star3.png";
        }
        else if (serviceCode == "****")
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star4.png";
        }
        else
        {
            ReviewList[i].SERVICE.SERVICE_DESC = "star0.png";
        }
    }

Body:
If you know each item will consist of a number of stars, why not do this?:

for (int i = 0; i < ReviewList.Count; i++)
{
    string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC;
    ReviewList[i].SERVICE.SERVICE_DESC = "star" + serviceCode.Length + ".png";
}


问:
pTextServices->TxSendMessage( EM_STREAMIN, ( WPARAM ) SF_RTF, ( LPARAM ) &editStream, &lResult ) does not call EditStreamInCallback
When calling:
pTextServices->TxSendMessage( EM_STREAMIN, ( WPARAM ) SF_RTF, ( LPARAM ) &editStream, &lResult )

editSteam.EditStreamInCallback is not being called, but if SF_TEXT is used instead of SF_RTF, then editSteam.EditStreamInCallback gets called.

According to MS docs:
https://learn.microsoft.com/en-us/windows/win32/api/richedit/nc-richedit-editstreamcallback

An error occurs that prevents the rich edit control from transferring
data into or out of itself. Examples are out-of-memory situations,
failure of a system function, or an invalid character in the read
buffer.

In these cases editStream.dwError should contain a different value from zero, but it is zero.

This is the used RTF: "{\rtf1\ansi\pard test \par}" in the code escaped as:

```<code>"{\\rtf1\\ansi\\pard test \\par}"
</code>```

Thank you

答:
Fixed and working fine thanks to my friend Mr. Bruno Cantero (C3)</p>
```<code>#include <Richedit.h>
#include <textserv.h>

typedef struct
{
   char * szText;
   LONG lSize;
   LONG lCount;
} RTFTEXTINFO;

typedef HRESULT ( _stdcall * PCREATETEXTSERVICES ) ( IUnknown *, ITextHost *, IUnknown ** );

const IID IID_ITextServices = { 0x8d33f740, 0xcf58, 0x11ce, { 0xa8, 0x9d, 0x00, 0xaa, 0x00, 0x6c, 0xad, 0xc5 } };

class TTextHost : public ITextHost
{
   public:
      /* IUnknown */
      STDMETHOD( QueryInterface )( REFIID, PVOID * ppvObject ) { * ppvObject = NULL; return S_FALSE; };
      STDMETHOD_( ULONG, AddRef )( void ) { return 0; };
      STDMETHOD_( ULONG, Release )( void ) { return 0; };

      /* ITextHost */
      HDC TxGetDC( void ) { return NULL; };
      INT TxReleaseDC( HDC ) { return 1; };
      BOOL TxShowScrollBar( INT, BOOL ) { return FALSE; };
      BOOL TxEnableScrollBar( INT, INT ) { return FALSE; };
      BOOL TxSetScrollRange( INT, LONG, INT, BOOL ) { return FALSE; };
      BOOL TxSetScrollPos( INT, INT, BOOL ) { return FALSE; };
      void TxInvalidateRect( LPCRECT, BOOL ) {};
      void TxViewChange( BOOL ) {};
      BOOL TxCreateCaret( HBITMAP, INT, INT ) { return FALSE; };
      BOOL TxShowCaret( BOOL ) { return FALSE; };
      BOOL TxSetCaretPos( INT, INT ) { return FALSE; };
      BOOL TxSetTimer( UINT, UINT ) { return FALSE; };
      void TxKillTimer( UINT ) {};
      void TxScrollWindowEx( INT, INT, LPCRECT, LPCRECT, HRGN, LPRECT, UINT ) {};
      void TxSetCapture( BOOL ) {};
      void TxSetFocus( void ) {};
      void TxSetCursor( HCURSOR, BOOL ) {};
      BOOL TxScreenToClient( LPPOINT ) { return FALSE; };
      BOOL TxClientToScreen( LPPOINT ) { return FALSE; };
      HRESULT TxActivate( LONG * ) { return S_OK; };
      HRESULT TxDeactivate( LONG ) { return S_OK; };
      HRESULT TxGetClientRect( LPRECT prc ) { SetRectEmpty( prc ); return S_OK; };
      HRESULT TxGetViewInset( LPRECT prc ) { SetRectEmpty( prc ); return S_OK; };
      HRESULT TxGetCharFormat( const CHARFORMATW ** ppCF ) { * ppCF = FCharFormat; return S_OK; };
      HRESULT TxGetParaFormat( const PARAFORMAT ** ppPF ) { * ppPF = FParaFormat; return S_OK; };
      COLORREF TxGetSysColor( int iIndex ) { return GetSysColor( iIndex ); };
      HRESULT TxGetBackStyle( TXTBACKSTYLE * pstyle ) { * pstyle = TXTBACK_TRANSPARENT; return S_OK; };
      HRESULT TxGetMaxLength( DWORD * plength ) { * plength = INFINITE; return S_OK; };
      HRESULT TxGetScrollBars( DWORD * pdwScrollBar ) { * pdwScrollBar = 0; return S_OK; };
      HRESULT TxGetPasswordChar( _Out_ TCHAR * pch ) { return S_FALSE; };
      HRESULT TxGetAcceleratorPos( LONG * pcp ) { * pcp = -1; return S_OK; };
      HRESULT TxGetExtent( LPSIZEL ) { return E_NOTIMPL; };
      HRESULT OnTxCharFormatChange( const CHARFORMATW * pCF ) { _bcopy( FCharFormat, ( void * ) pCF, pCF->cbSize ); return S_OK; };
      HRESULT OnTxParaFormatChange( const PARAFORMAT * pPF ) { _bcopy( FParaFormat, ( void * ) pPF, pPF->cbSize ); return S_OK; };
      HRESULT TxGetPropertyBits( DWORD, DWORD * pdwBits ) { * pdwBits = TXTBIT_RICHTEXT | TXTBIT_MULTILINE | TXTBIT_WORDWRAP | TXTBIT_USECURRENTBKG; return S_OK; };
      HRESULT TxNotify( DWORD, void * ) { return S_OK; };
      HIMC TxImmGetContext( void ) { return NULL; };
      void TxImmReleaseContext( HIMC ) {};
      HRESULT TxGetSelectionBarWidth( LONG * lSelBarWidth ) { * lSelBarWidth = 100; return S_OK; };

      CHARFORMATW * FCharFormat;
      PARAFORMAT * FParaFormat;
};

static DWORD CALLBACK EditStreamCallback( DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG * pcb )
{
   RTFTEXTINFO * pRtfTextInfo;

   pRtfTextInfo = ( RTFTEXTINFO * ) dwCookie;

   if( pRtfTextInfo->lSize - pRtfTextInfo->lCount < cb )
      * pcb = pRtfTextInfo->lSize - pRtfTextInfo->lCount;
   else
      * pcb = cb;

   memcpy( pbBuff, pRtfTextInfo->szText, * pcb );
   pRtfTextInfo->lCount += * pcb;

   return 0;
}

extern "C" void SayRTF( void )
{
   LRESULT lResult;
   HDC hDC;
   HFONT hFont;
   HMODULE hDLL;
   RECT stRect;
   LOGFONT stLogFont;
   EDITSTREAM stEditStream;
   PCREATETEXTSERVICES pCreateTextServices;
   CHARFORMATW stCharFormat;
   PARAFORMAT stParaFormat;
   RTFTEXTINFO sRtfTextInfo;
   IUnknown * pUnknown;
   ITextServices * pTextServices;
   TTextHost * pTextHost;

   /* HDC donde dibujar. */
   hDC = ( HDC ) hb_parnl( 1 ); // the hDC where you want to show the RTF

   // Comentamos para probar la transperencia Rectangle( hDC, 9, 9, 202, 202 );

   stRect = { 10, 10, 200, 200 };
   hDLL = LoadLibrary( "Riched20.dll" );

   if( hDLL == NULL )
      return;

   pCreateTextServices = ( PCREATETEXTSERVICES ) GetProcAddress( hDLL, "CreateTextServices" );

   if( pCreateTextServices == NULL )
   {
      FreeLibrary( hDLL );

      return;
   }

   /* Obtenemos las características de la fuente del HDC. */
   hFont = ( HFONT ) SelectObject( hDC, GetStockObject( SYSTEM_FONT ) );
   GetObject( hFont, sizeof( LOGFONT ), &stLogFont );
   SelectObject( hDC, hFont );

   /* Creamos el formato de la fuente por defecto. */
   memset( &stCharFormat, 0, sizeof( CHARFORMATW ) );
   stCharFormat.cbSize = sizeof( CHARFORMATW );
   stCharFormat.dwEffects = CFM_EFFECTS | CFE_AUTOBACKCOLOR;
   stCharFormat.dwEffects &= ~( CFE_PROTECTED | CFE_LINK | CFE_AUTOCOLOR );

   if( stLogFont.lfWeight < FW_BOLD )
      stCharFormat.dwEffects &= ~CFE_BOLD;

   if( !stLogFont.lfItalic )
      stCharFormat.dwEffects &= ~CFE_ITALIC;

   if( !stLogFont.lfUnderline )
      stCharFormat.dwEffects &= ~CFE_UNDERLINE;

   if( !stLogFont.lfStrikeOut )
      stCharFormat.dwEffects &= ~CFE_STRIKEOUT;

   stCharFormat.dwMask = CFM_ALL | CFM_BACKCOLOR | CFM_STYLE;
   stCharFormat.bCharSet = stLogFont.lfCharSet;
   stCharFormat.bPitchAndFamily = stLogFont.lfPitchAndFamily;
   stCharFormat.yHeight = -stLogFont.lfHeight * 1440 / GetDeviceCaps( hDC, LOGPIXELSY );
   MultiByteToWideChar( CP_ACP, 0, stLogFont.lfFaceName, LF_FACESIZE, stCharFormat.szFaceName, LF_FACESIZE );

   /* Creamos el formato de párrafo por defecto. */
   memset( &stParaFormat, 0, sizeof( PARAFORMAT ) );
   stParaFormat.cbSize = sizeof( PARAFORMAT );
   stParaFormat.dwMask = PFM_ALL;
    stParaFormat.wAlignment = PFA_LEFT;
    stParaFormat.cTabCount = 1;
    stParaFormat.rgxTabs[ 0 ] = lDefaultTab;

   /* Instanciamos nuestro objeto host. */
   pTextHost = new TTextHost;
   pTextHost->FCharFormat = &stCharFormat;
   pTextHost->FParaFormat = &stParaFormat;

   /* Creamos el objeto IUnknown y lo asociamos a nuestro objeto TTextHost. */
   if( pCreateTextServices( NULL, pTextHost, &pUnknown ) != S_OK )
   {
      delete pTextHost;
      FreeLibrary( hDLL );

      return;
   }

   /* Obtenemos el interface ITextServices. */
   pTextServices = NULL;
   pUnknown->QueryInterface( IID_ITextServices, ( void ** ) &pTextServices );

   /* Liberamos el objeto IUnknown. */
   pUnknown->Release();

   if( pTextServices != NULL )
   {
//      sRtfTextInfo.szText = "Plaint Text";
      sRtfTextInfo.szText = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fswiss\\fprq2\\fcharset0 Tahoma;}{\\f1\\fswiss\\fcharset0 Arial;}}{\\colortbl ;\\red128\\green0\\blue0;\\red0\\green0\\blue128;\\red0\\green128\\blue0;}\\viewkind4\\uc1\\pard\\f0\\fs20 H\\fs24 E\\b L\\ul\\fs20 L\\i O\\ulnone\\b0\\i0   \\cf1 W\\b\\fs22 O\\cf2\\ul\\b0 R\\i\\fs28 L\\cf3\\ulnone\\b\\i0\\fs20 D\\cf0\\b0\\f1\\par}";
      sRtfTextInfo.lSize = lstrlen( sRtfTextInfo.szText );
      sRtfTextInfo.lCount = 0;
      stEditStream.dwCookie = ( DWORD_PTR ) &sRtfTextInfo;
      stEditStream.pfnCallback = EditStreamCallback;

//      if( pTextServices->TxSendMessage( EM_STREAMIN, SF_TEXT, ( LPARAM ) &stEditStream, &lResult ) == S_OK )
      if( pTextServices->TxSendMessage( EM_STREAMIN, SF_RTF, ( LPARAM ) &stEditStream, &lResult ) == S_OK )
         pTextServices->TxDraw( DVASPECT_CONTENT, 0, NULL, NULL, hDC, NULL, ( RECTL * ) &stRect, NULL, NULL, NULL, 0, TXTVIEW_INACTIVE );

      /* Liberamos el objeto ITextServices. */
      pTextServices->Release();
   }

   delete pTextHost;
   FreeLibrary( hDLL );
}
</code>```

Body:
When calling:
pTextServices->TxSendMessage( EM_STREAMIN, ( WPARAM ) SF_RTF, ( LPARAM ) &editStream, &lResult )

editSteam.EditStreamInCallback is not being called, but if SF_TEXT is used instead of SF_RTF, then editSteam.EditStreamInCallback gets called.

According to MS docs:
https://learn.microsoft.com/en-us/windows/win32/api/richedit/nc-richedit-editstreamcallback

An error occurs that prevents the rich edit control from transferring
data into or out of itself. Examples are out-of-memory situations,
failure of a system function, or an invalid character in the read
buffer.

In these cases editStream.dwError should contain a different value from zero, but it is zero.

This is the used RTF: "{\rtf1\ansi\pard test \par}" in the code escaped as:

"{\\rtf1\\ansi\\pard test \\par}"

Thank you

Body:
Fixed and working fine thanks to my friend Mr. Bruno Cantero (C3)

#include <Richedit.h>
#include <textserv.h>

typedef struct
{
   char * szText;
   LONG lSize;
   LONG lCount;
} RTFTEXTINFO;

typedef HRESULT ( _stdcall * PCREATETEXTSERVICES ) ( IUnknown *, ITextHost *, IUnknown ** );

const IID IID_ITextServices = { 0x8d33f740, 0xcf58, 0x11ce, { 0xa8, 0x9d, 0x00, 0xaa, 0x00, 0x6c, 0xad, 0xc5 } };

class TTextHost : public ITextHost
{
   public:
      /* IUnknown */
      STDMETHOD( QueryInterface )( REFIID, PVOID * ppvObject ) { * ppvObject = NULL; return S_FALSE; };
      STDMETHOD_( ULONG, AddRef )( void ) { return 0; };
      STDMETHOD_( ULONG, Release )( void ) { return 0; };

      /* ITextHost */
      HDC TxGetDC( void ) { return NULL; };
      INT TxReleaseDC( HDC ) { return 1; };
      BOOL TxShowScrollBar( INT, BOOL ) { return FALSE; };
      BOOL TxEnableScrollBar( INT, INT ) { return FALSE; };
      BOOL TxSetScrollRange( INT, LONG, INT, BOOL ) { return FALSE; };
      BOOL TxSetScrollPos( INT, INT, BOOL ) { return FALSE; };
      void TxInvalidateRect( LPCRECT, BOOL ) {};
      void TxViewChange( BOOL ) {};
      BOOL TxCreateCaret( HBITMAP, INT, INT ) { return FALSE; };
      BOOL TxShowCaret( BOOL ) { return FALSE; };
      BOOL TxSetCaretPos( INT, INT ) { return FALSE; };
      BOOL TxSetTimer( UINT, UINT ) { return FALSE; };
      void TxKillTimer( UINT ) {};
      void TxScrollWindowEx( INT, INT, LPCRECT, LPCRECT, HRGN, LPRECT, UINT ) {};
      void TxSetCapture( BOOL ) {};
      void TxSetFocus( void ) {};
      void TxSetCursor( HCURSOR, BOOL ) {};
      BOOL TxScreenToClient( LPPOINT ) { return FALSE; };
      BOOL TxClientToScreen( LPPOINT ) { return FALSE; };
      HRESULT TxActivate( LONG * ) { return S_OK; };
      HRESULT TxDeactivate( LONG ) { return S_OK; };
      HRESULT TxGetClientRect( LPRECT prc ) { SetRectEmpty( prc ); return S_OK; };
      HRESULT TxGetViewInset( LPRECT prc ) { SetRectEmpty( prc ); return S_OK; };
      HRESULT TxGetCharFormat( const CHARFORMATW ** ppCF ) { * ppCF = FCharFormat; return S_OK; };
      HRESULT TxGetParaFormat( const PARAFORMAT ** ppPF ) { * ppPF = FParaFormat; return S_OK; };
      COLORREF TxGetSysColor( int iIndex ) { return GetSysColor( iIndex ); };
      HRESULT TxGetBackStyle( TXTBACKSTYLE * pstyle ) { * pstyle = TXTBACK_TRANSPARENT; return S_OK; };
      HRESULT TxGetMaxLength( DWORD * plength ) { * plength = INFINITE; return S_OK; };
      HRESULT TxGetScrollBars( DWORD * pdwScrollBar ) { * pdwScrollBar = 0; return S_OK; };
      HRESULT TxGetPasswordChar( _Out_ TCHAR * pch ) { return S_FALSE; };
      HRESULT TxGetAcceleratorPos( LONG * pcp ) { * pcp = -1; return S_OK; };
      HRESULT TxGetExtent( LPSIZEL ) { return E_NOTIMPL; };
      HRESULT OnTxCharFormatChange( const CHARFORMATW * pCF ) { _bcopy( FCharFormat, ( void * ) pCF, pCF->cbSize ); return S_OK; };
      HRESULT OnTxParaFormatChange( const PARAFORMAT * pPF ) { _bcopy( FParaFormat, ( void * ) pPF, pPF->cbSize ); return S_OK; };
      HRESULT TxGetPropertyBits( DWORD, DWORD * pdwBits ) { * pdwBits = TXTBIT_RICHTEXT | TXTBIT_MULTILINE | TXTBIT_WORDWRAP | TXTBIT_USECURRENTBKG; return S_OK; };
      HRESULT TxNotify( DWORD, void * ) { return S_OK; };
      HIMC TxImmGetContext( void ) { return NULL; };
      void TxImmReleaseContext( HIMC ) {};
      HRESULT TxGetSelectionBarWidth( LONG * lSelBarWidth ) { * lSelBarWidth = 100; return S_OK; };

      CHARFORMATW * FCharFormat;
      PARAFORMAT * FParaFormat;
};

static DWORD CALLBACK EditStreamCallback( DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG * pcb )
{
   RTFTEXTINFO * pRtfTextInfo;

   pRtfTextInfo = ( RTFTEXTINFO * ) dwCookie;

   if( pRtfTextInfo->lSize - pRtfTextInfo->lCount < cb )
      * pcb = pRtfTextInfo->lSize - pRtfTextInfo->lCount;
   else
      * pcb = cb;

   memcpy( pbBuff, pRtfTextInfo->szText, * pcb );
   pRtfTextInfo->lCount += * pcb;

   return 0;
}

extern "C" void SayRTF( void )
{
   LRESULT lResult;
   HDC hDC;
   HFONT hFont;
   HMODULE hDLL;
   RECT stRect;
   LOGFONT stLogFont;
   EDITSTREAM stEditStream;
   PCREATETEXTSERVICES pCreateTextServices;
   CHARFORMATW stCharFormat;
   PARAFORMAT stParaFormat;
   RTFTEXTINFO sRtfTextInfo;
   IUnknown * pUnknown;
   ITextServices * pTextServices;
   TTextHost * pTextHost;

   /* HDC donde dibujar. */
   hDC = ( HDC ) hb_parnl( 1 ); // the hDC where you want to show the RTF

   // Comentamos para probar la transperencia Rectangle( hDC, 9, 9, 202, 202 );

   stRect = { 10, 10, 200, 200 };
   hDLL = LoadLibrary( "Riched20.dll" );

   if( hDLL == NULL )
      return;

   pCreateTextServices = ( PCREATETEXTSERVICES ) GetProcAddress( hDLL, "CreateTextServices" );

   if( pCreateTextServices == NULL )
   {
      FreeLibrary( hDLL );

      return;
   }

   /* Obtenemos las características de la fuente del HDC. */
   hFont = ( HFONT ) SelectObject( hDC, GetStockObject( SYSTEM_FONT ) );
   GetObject( hFont, sizeof( LOGFONT ), &stLogFont );
   SelectObject( hDC, hFont );

   /* Creamos el formato de la fuente por defecto. */
   memset( &stCharFormat, 0, sizeof( CHARFORMATW ) );
   stCharFormat.cbSize = sizeof( CHARFORMATW );
   stCharFormat.dwEffects = CFM_EFFECTS | CFE_AUTOBACKCOLOR;
   stCharFormat.dwEffects &= ~( CFE_PROTECTED | CFE_LINK | CFE_AUTOCOLOR );

   if( stLogFont.lfWeight < FW_BOLD )
      stCharFormat.dwEffects &= ~CFE_BOLD;

   if( !stLogFont.lfItalic )
      stCharFormat.dwEffects &= ~CFE_ITALIC;

   if( !stLogFont.lfUnderline )
      stCharFormat.dwEffects &= ~CFE_UNDERLINE;

   if( !stLogFont.lfStrikeOut )
      stCharFormat.dwEffects &= ~CFE_STRIKEOUT;

   stCharFormat.dwMask = CFM_ALL | CFM_BACKCOLOR | CFM_STYLE;
   stCharFormat.bCharSet = stLogFont.lfCharSet;
   stCharFormat.bPitchAndFamily = stLogFont.lfPitchAndFamily;
   stCharFormat.yHeight = -stLogFont.lfHeight * 1440 / GetDeviceCaps( hDC, LOGPIXELSY );
   MultiByteToWideChar( CP_ACP, 0, stLogFont.lfFaceName, LF_FACESIZE, stCharFormat.szFaceName, LF_FACESIZE );

   /* Creamos el formato de párrafo por defecto. */
   memset( &stParaFormat, 0, sizeof( PARAFORMAT ) );
   stParaFormat.cbSize = sizeof( PARAFORMAT );
   stParaFormat.dwMask = PFM_ALL;
    stParaFormat.wAlignment = PFA_LEFT;
    stParaFormat.cTabCount = 1;
    stParaFormat.rgxTabs[ 0 ] = lDefaultTab;

   /* Instanciamos nuestro objeto host. */
   pTextHost = new TTextHost;
   pTextHost->FCharFormat = &stCharFormat;
   pTextHost->FParaFormat = &stParaFormat;

   /* Creamos el objeto IUnknown y lo asociamos a nuestro objeto TTextHost. */
   if( pCreateTextServices( NULL, pTextHost, &pUnknown ) != S_OK )
   {
      delete pTextHost;
      FreeLibrary( hDLL );

      return;
   }

   /* Obtenemos el interface ITextServices. */
   pTextServices = NULL;
   pUnknown->QueryInterface( IID_ITextServices, ( void ** ) &pTextServices );

   /* Liberamos el objeto IUnknown. */
   pUnknown->Release();

   if( pTextServices != NULL )
   {
//      sRtfTextInfo.szText = "Plaint Text";
      sRtfTextInfo.szText = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fswiss\\fprq2\\fcharset0 Tahoma;}{\\f1\\fswiss\\fcharset0 Arial;}}{\\colortbl ;\\red128\\green0\\blue0;\\red0\\green0\\blue128;\\red0\\green128\\blue0;}\\viewkind4\\uc1\\pard\\f0\\fs20 H\\fs24 E\\b L\\ul\\fs20 L\\i O\\ulnone\\b0\\i0   \\cf1 W\\b\\fs22 O\\cf2\\ul\\b0 R\\i\\fs28 L\\cf3\\ulnone\\b\\i0\\fs20 D\\cf0\\b0\\f1\\par}";
      sRtfTextInfo.lSize = lstrlen( sRtfTextInfo.szText );
      sRtfTextInfo.lCount = 0;
      stEditStream.dwCookie = ( DWORD_PTR ) &sRtfTextInfo;
      stEditStream.pfnCallback = EditStreamCallback;

//      if( pTextServices->TxSendMessage( EM_STREAMIN, SF_TEXT, ( LPARAM ) &stEditStream, &lResult ) == S_OK )
      if( pTextServices->TxSendMessage( EM_STREAMIN, SF_RTF, ( LPARAM ) &stEditStream, &lResult ) == S_OK )
         pTextServices->TxDraw( DVASPECT_CONTENT, 0, NULL, NULL, hDC, NULL, ( RECTL * ) &stRect, NULL, NULL, NULL, 0, TXTVIEW_INACTIVE );

      /* Liberamos el objeto ITextServices. */
      pTextServices->Release();
   }

   delete pTextHost;
   FreeLibrary( hDLL );
}


问:
R handle vector values in addition to scalar values with rounding function
```<code>round2 <- function(x, y) {
  if(is.na(x)) { return ('') }
  return(paste0(round(100 * x, 0), '% ', round(100 * y, 0), '%'))
}

mydf <- data.frame(a = c(NA, .323, .555), b = c(NA, .232, .541))
mydf %>% dplyr::mutate(c = round2(a, b))
</code>```

The main part of the function paste0(round(...)) works just fine, however the if(is.na(x)) { return ('') } does not properly handle that x and y are vectors. As a result, the entire column c in mydf is an empty string. How can we update this so only the first row in mydf returns an empty string?

答:
the if () function if you pass a vector, it will only take the first value of vector..
also a warning will be displayed on console..

better you pass the vector in function call and use the
for call up to length of vector and check each x[j] j=1:length(x)

or you can use

vec
[1]  2  3 NA
sum(is.na(vec))
[1] 1

something like this in your logic building..

Body:
round2 <- function(x, y) {
  if(is.na(x)) { return ('') }
  return(paste0(round(100 * x, 0), '% ', round(100 * y, 0), '%'))
}

mydf <- data.frame(a = c(NA, .323, .555), b = c(NA, .232, .541))
mydf %>% dplyr::mutate(c = round2(a, b))

The main part of the function paste0(round(...)) works just fine, however the if(is.na(x)) { return ('') } does not properly handle that x and y are vectors. As a result, the entire column c in mydf is an empty string. How can we update this so only the first row in mydf returns an empty string?


问:
a document path must be a non-empty string 'package:cloud_firestore/src/collection_reference.dart'Failed assertion: line 116 pos 14: 'path.isNotEmpty'

Widget catageriesList(String airportId, locationId) {
    return Container(
      child: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection("Airport").doc(widget.airportId).collection("location").doc(locationId).collection("Catagorie").snapshots(),
        builder: (context, snapshot) {
          return snapshot.data == null
              ? Container() : ListView.builder(
              itemCount: snapshot.data!.docs.length,
              itemBuilder: (context, index) {
                DocumentSnapshot data = snapshot.data!.docs[index];
                print("object");
                return Catageries(
                  catagerieId: data["Catagorie_id"],
                  catagerieName:  data["Catagorie_name"],
                );
              }
          );
        },
      ),
    );
  }
```

答:
The error means you're passing null as a document path and this is in this line:

        stream: FirebaseFirestore.instance.collection("Airport").doc(widget.airportId).collection("location").doc(locationId).collection("Catagorie").snapshots(),
```
<p>This means <code>widget.airportId</code> is null.</p>
<p><strong>Solution:</strong></p>
<p>You method <code>catageriesList</code> has an used argument <code>airportId</code> which you should be pass as the document path.</p>
<p>Update this line of code:</p>
<pre class="lang-dart prettyprint-override"><code>stream: FirebaseFirestore.instance.collection("Airport").doc(widget.airportId).collection("location").doc(locationId).collection("Catagorie").snapshots(),
</code>```

to this:

stream: FirebaseFirestore.instance.collection("Airport").doc(airportId).collection("location").doc(locationId).collection("Catagorie").snapshots(),
```

Body:
The error means you're passing null as a document path and this is in this line:

        stream: FirebaseFirestore.instance.collection("Airport").doc(widget.airportId).collection("location").doc(locationId).collection("Catagorie").snapshots(),

This means widget.airportId is null.

Solution:

You method catageriesList has an used argument airportId which you should be pass as the document path.

Update this line of code:

stream: FirebaseFirestore.instance.collection("Airport").doc(widget.airportId).collection("location").doc(locationId).collection("Catagorie").snapshots(),

to this:

stream: FirebaseFirestore.instance.collection("Airport").doc(airportId).collection("location").doc(locationId).collection("Catagorie").snapshots(),


问:
How to remove parenthesis from output python
So I have a function that keeps spitting out:

```<code>(10.3,11.4)
</code>```

when it should be spitting out:

```<code>10.3 11.4
</code>```

I played around and wrote a simple python code and I seem to understand the concept

```<code>a=3
b=3
print a,b #returns 3 3
</code>```

but it is not working for the function below, so I am wondering why it keeps returning the ()

```<code>import math

x=10.01
y=9.01

def d():
    b = 2.00 *  x / math.sqrt(7)
    q=round(y-b,2)
    r=round(y+b,2)
    return q,r

print d() #returns (1.4399999999999999, 16.579999999999998)
</code>```

答:
math.sqrt return a complex number with a real and an imaginary part.
Change it into math.sqrt(7).real and the complex number is a real number only.  This make the print do as you expect</p>

Body:
So I have a function that keeps spitting out:

(10.3,11.4)

when it should be spitting out:

10.3 11.4

I played around and wrote a simple python code and I seem to understand the concept

a=3
b=3
print a,b #returns 3 3

but it is not working for the function below, so I am wondering why it keeps returning the ()

import math

x=10.01
y=9.01

def d():
    b = 2.00 *  x / math.sqrt(7)
    q=round(y-b,2)
    r=round(y+b,2)
    return q,r

print d() #returns (1.4399999999999999, 16.579999999999998)


问:
sortwith one of the POJO values?
I have random pojo values, and I want to sort by one of the POJO values, the structure of the values I want to sort is as follows: A-1, A-2, A-3, A-4, A-5, .. .

I've tried to sort it but the value is really in order only between A-1 to A-9, while the value for A-10 is always under A-1.

here's the code I use:

```<code>temp.sortWith { lhs, rhs ->
  rhs?.blok_kamar?.let {
  lhs?.blok_kamar?.compareTo(
    it, false
  )}!!
}
</code>```

Please help.

答:
This is how lexicographical ordering works. "1000" is less than "2", despite 1000 being greater than 2. Look at the quotes. It seems like your A-1, A-2, ..., A-10 are Strings. You need to extract the numbers from those identifiers and compare them as Ints:

```<code>data class Data(val id: String)

fun main() {
    val list = mutableListOf(
        Data("A-1"),
        Data("A-10"),
        Data("A-2"),
        Data("A-30"),
        Data("A-3")
    )

    list.sortBy { it.id.substring(it.id.indexOf("-") + 1).toInt() }
    println(list)
}
</code>```

This prints:

```<code>[Data(id=A-1), Data(id=A-2), Data(id=A-3), Data(id=A-10), Data(id=A-30)]
</code>```

Title: sortwith one of the POJO values?

Body:
I have random pojo values, and I want to sort by one of the POJO values, the structure of the values I want to sort is as follows: A-1, A-2, A-3, A-4, A-5, .. .

I've tried to sort it but the value is really in order only between A-1 to A-9, while the value for A-10 is always under A-1.

here's the code I use:

temp.sortWith { lhs, rhs ->
  rhs?.blok_kamar?.let {
  lhs?.blok_kamar?.compareTo(
    it, false
  )}!!
}

Please help.

Body:
This is how lexicographical ordering works. "1000" is less than "2", despite 1000 being greater than 2. Look at the quotes. It seems like your A-1, A-2, ..., A-10 are Strings. You need to extract the numbers from those identifiers and compare them as Ints:

data class Data(val id: String)

fun main() {
    val list = mutableListOf(
        Data("A-1"),
        Data("A-10"),
        Data("A-2"),
        Data("A-30"),
        Data("A-3")
    )

    list.sortBy { it.id.substring(it.id.indexOf("-") + 1).toInt() }
    println(list)
}

This prints:

[Data(id=A-1), Data(id=A-2), Data(id=A-3), Data(id=A-10), Data(id=A-30)]


问:
How can I create a Group_Concat field per table using values from other records
Suppose a table of First and Last Names and for each record I want to do comma-delimited list of relatives.

1ST | LAST | RELATIVES

Bob | Smith | Alice,Andrew

Alice | Smith | Bob,Andrew

Andrew |Smith | Bob,Alice

Alex | Jones | Anny, Ricky

Anny | Jones | Alex, Ricky

Ricky | Jones | Alex, Anny

As per this sqlFiddle

http://sqlfiddle.com/#!9/25d80c/1

I know how to group_contact manually for any last name but am unclear how for each record I could have it go find the records with matching last name and run the same group_concat

答:
You can do it with a self LEFT join and aggregation:

```<code>SELECT s1.First, s1.Last,
       GROUP_CONCAT(s2.First) Relatives
FROM Surnames s1 LEFT JOIN Surnames s2
ON s2.Last = s1.Last AND s2.First <> s1.First
GROUP BY s1.First, s1.Last;
</code>```

See the demo.

Body:
You can do it with a self LEFT join and aggregation:

SELECT s1.First, s1.Last,
       GROUP_CONCAT(s2.First) Relatives
FROM Surnames s1 LEFT JOIN Surnames s2
ON s2.Last = s1.Last AND s2.First <> s1.First
GROUP BY s1.First, s1.Last;

See the demo.


问:
Webscraping: How to skip getelement when element/webpage doesn't exist?
I am scraping data from a website (thousands of different pages from the website), however, some of the webpages I try to navigate to don't exist or don't have the element/tag I need, these cases result in a bug prompt appearing and my code stops running. Because I am running through so many pages, I would prefer for my code just to return a blank/ignore them and move on.

I tried to use an iferror then null type statement for both the Price and WatchlistCount variables below, but this hasn't worked. Can you please help?

The code below is what I'm using to navigate to and scrape the webpages. The code before this creates the URLs that I need.

```<code>  Sub CM_Watchlist2000()

'Declaration
Dim Watchlist As Workbook
Dim Inp As Worksheet
Dim Inp2 As Worksheet
Dim ie As InternetExplorer
Dim doc As HTMLDocument
Dim i As Long
Dim iStart As Long

'Initialisation of Coinmarketcap and spreadsheet
Set Watchlist = Workbooks("Watchlist.xlsm")
Set Inp = Watchlist.Worksheets("Top 2000")
Set Inp2 = Watchlist.Worksheets("Lookup")
Set ie = New InternetExplorer

iStart = 0

For i = iStart To 100

Inp.Activate

    Range("A2").Offset(i, 0).Select
    Selection.Copy

Inp2.Activate

    Range("B1").Select
     Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=True

ie.Visible = True
ie.Navigate Inp2.Range("D1")

'Waits until webpage is open before running macro
Do Until ie.ReadyState = READYSTATE_COMPLETE
   DoEvents
Loop

Set doc = ie.Document
Price = doc.getElementsByClassName("priceValue ")(0).innerText
WatchlistCount = doc.getElementsByClassName("namePill")(2).innerText

Inp.Activate

    Range("B2").Offset(i, 0) = Price
    Range("C2").Offset(i, 0) = WatchlistCount

Next i

End Sub
</code>```

答:
Scrape Error Handling (IE)

This could possibly be improved if you could share the preceding code.

Option Explicit

Sub Scrape()

    Dim ErrNum As Long
    Dim j As Long

    For i = ? to ?

        Set doc = ie.Document

        If Not doc Is Nothing Then

            On Error Resume Next
                Price = doc.getElementsByClassName("priceValue ")(0).innerText
                WatchlistCount = doc.getElementsByClassName("namePill")(2).innerText
                ErrNum = Err.Number
            On Error GoTo 0

            If ErrNum = 0 Then
                inp.Range("B2").Offset(j, 0) = Price
                inp.Range("C2").Offset(j, 0) = WatchlistCount
                j = j + 1
            Else
                ErrNum = 0
            End If

            Set doc = Nothing

        End If

    Next i

End Sub
```

Body:
I am scraping data from a website (thousands of different pages from the website), however, some of the webpages I try to navigate to don't exist or don't have the element/tag I need, these cases result in a bug prompt appearing and my code stops running. Because I am running through so many pages, I would prefer for my code just to return a blank/ignore them and move on.

I tried to use an iferror then null type statement for both the Price and WatchlistCount variables below, but this hasn't worked. Can you please help?

The code below is what I'm using to navigate to and scrape the webpages. The code before this creates the URLs that I need.

  Sub CM_Watchlist2000()

'Declaration
Dim Watchlist As Workbook
Dim Inp As Worksheet
Dim Inp2 As Worksheet
Dim ie As InternetExplorer
Dim doc As HTMLDocument
Dim i As Long
Dim iStart As Long

'Initialisation of Coinmarketcap and spreadsheet
Set Watchlist = Workbooks("Watchlist.xlsm")
Set Inp = Watchlist.Worksheets("Top 2000")
Set Inp2 = Watchlist.Worksheets("Lookup")
Set ie = New InternetExplorer

iStart = 0

For i = iStart To 100

Inp.Activate

    Range("A2").Offset(i, 0).Select
    Selection.Copy

Inp2.Activate

    Range("B1").Select
     Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=True

ie.Visible = True
ie.Navigate Inp2.Range("D1")

'Waits until webpage is open before running macro
Do Until ie.ReadyState = READYSTATE_COMPLETE
   DoEvents
Loop

Set doc = ie.Document
Price = doc.getElementsByClassName("priceValue ")(0).innerText
WatchlistCount = doc.getElementsByClassName("namePill")(2).innerText

Inp.Activate

    Range("B2").Offset(i, 0) = Price
    Range("C2").Offset(i, 0) = WatchlistCount

Next i

End Sub


问:
Get specific value from json object
I have a json file with the following structure:

```<code>"edition": 979,
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Gray"
    },
    {
      "trait_type": "Base",
      "value": "Guy"
    },
    {
      "trait_type": "Body",
      "value": "FormalBlack"
    },
    {
      "trait_type": "Hand",
      "value": "None"
    },
    {
      "trait_type": "Head",
      "value": "Astronaut"
    },
    {
      "trait_type": "Pet",
      "value": "OrangeCat"
    }
  ],
  "properties": {
    "files": [
      {
        "uri": "979.png",
        "type": "image/png"
      }
    ],
</code>```

How can I get get the data of 'value' in 'attributes'?
I can get the whole 'attributes' object but can't get to specific values inside, for example

```<code>f = open('./metadata/0.json')

xmp = json.load(f)

print (xmp['attributes'])
</code>```

returns

```<code>[{'trait_type': 'Background', 'value': 'Purple'}, {'trait_type': 'Base', 'value': 'RedGuy'}, {'trait_type': 'Body', 'value': 'Formal'}, {'trait_type': 'Hand', 'value': 'FlamingSword'}, {'trait_type': 'Head', 'value': 'RedHead'}, {'trait_type': 'Pet', 'value': 'None'}]
</code>```

but I only need the value portion. I can run another method to search through it to get what I want but I imagine there is a much easier way.

答:
To get all the values, you need to iterate on 'attributes' and take each 'value' value

xmp = {
    "attributes": [
        {"trait_type": "Background","value": "Gray"},
        {"trait_type": "Base","value": "Guy"},
        {"trait_type": "Body","value": "FormalBlack"},
        {"trait_type": "Hand","value": "None"},
        {"trait_type": "Head","value": "Astronaut"},
        {"trait_type": "Pet","value": "OrangeCat"}
    ],
}

values = [item['value'] for item in xmp['attributes']]
# ['Gray', 'Guy', 'FormalBlack', ... ]
```

Title: Get specific value from json object

Body:
I have a json file with the following structure:

"edition": 979,
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Gray"
    },
    {
      "trait_type": "Base",
      "value": "Guy"
    },
    {
      "trait_type": "Body",
      "value": "FormalBlack"
    },
    {
      "trait_type": "Hand",
      "value": "None"
    },
    {
      "trait_type": "Head",
      "value": "Astronaut"
    },
    {
      "trait_type": "Pet",
      "value": "OrangeCat"
    }
  ],
  "properties": {
    "files": [
      {
        "uri": "979.png",
        "type": "image/png"
      }
    ],

How can I get get the data of 'value' in 'attributes'?
I can get the whole 'attributes' object but can't get to specific values inside, for example

f = open('./metadata/0.json')

xmp = json.load(f)

print (xmp['attributes'])

returns

[{'trait_type': 'Background', 'value': 'Purple'}, {'trait_type': 'Base', 'value': 'RedGuy'}, {'trait_type': 'Body', 'value': 'Formal'}, {'trait_type': 'Hand', 'value': 'FlamingSword'}, {'trait_type': 'Head', 'value': 'RedHead'}, {'trait_type': 'Pet', 'value': 'None'}]

but I only need the value portion. I can run another method to search through it to get what I want but I imagine there is a much easier way.


问:
disableSelection on everything except input[type=text]
I am looking to use jQuery's "disableSelection()" function because I have a lot of drag and drop on the pages but I do not want to disable selection on input boxes, just everything else.

I have tried

```<code>$('body').disableSelection(); $('input').enableSelection();

$('body').not('input').disableSelection();
</code>```

still DISABLES EVERYTHING ON THE PAGE. Thank you.

答: I dont think so disableSelection will work for input textboxes. It's useful for making text elements, or elements that contain text, not text-selectable. For example, if you have a draggable element, you may not want text selection to occur when the user goes to drag the element.

Body:
I am looking to use jQuery's "disableSelection()" function because I have a lot of drag and drop on the pages but I do not want to disable selection on input boxes, just everything else.

I have tried

$('body').disableSelection(); $('input').enableSelection();

$('body').not('input').disableSelection();

still DISABLES EVERYTHING ON THE PAGE. Thank you.


答:
Just apply a simple filter to the list you already managed to extract:</p>
```<code>values = [x['value'] for x in xmp['attributes']]  # if you only want the values
dicts = [{'value': x['value']} for x in xmp['attributes']}  # if you need dicts
</code>```

Title: Get specific value from json object

Body:
Just apply a simple filter to the list you already managed to extract:

values = [x['value'] for x in xmp['attributes']]  # if you only want the values
dicts = [{'value': x['value']} for x in xmp['attributes']}  # if you need dicts


问:
How to inject repository dagger dependency instance in my integration tests?
I'm trying to access my repository dependency from my integration tests but I can't seem to find a way to do so.

```<code>@Singleton
@Component(
    modules = [
        RepositoryModule::class,
    ]
)
interface TestAppComponent : AppComponent {

    @Component.Builder
    interface Builder : AppComponent.Builder {

        override fun build(): TestAppComponent
    }
}
</code>```

The repository module

```<code>@Module
interface RepositoryModule {

    @Binds
    fun repository(repo: Repository): IRepository
}
</code>```

And in my integration test :

```<code>class AppIntegTests {

    @Inject
    lateinit var repository: IRepository

    @BeforeTest
    fun setup() {
        repository.deleteAll()
    }

    @Test
    fun testRoot() {
        withTestApplication(config) {
            handleRequest { method = HttpMethod.Get; uri = "/users" }.apply {
               assertEquals(HttpStatusCode.OK, response.status())
            }
            // tests....
        }
    }
}
</code>```

When doing this, I get lateinit property has not been initialized on my injected repository.
Is what I'm trying to do achievable with Dagger?

答:
You have to pass reference of AppIntegTests class to dagger graph in order to initialize lateinit property by dagger

Add inject function to TestAppComponent

```<code>interface TestAppComponent  {

    fun inject(test: AppIntegTests)

    @Component.Builder
    interface Builder {
        fun build(): TestAppComponent
    }
}
</code>```

call this method from setUp function of AppIntegTests

```<code>class AppIntegTests {

    @Inject
    lateinit var repository: IRepository

    @Before
    fun setup() {
        val testAppComponent = DaggerTestAppComponent.builder().build()
        testAppComponent.inject(this)

        repository.deleteAll()
    }
</code>```

Body:
I'm trying to access my repository dependency from my integration tests but I can't seem to find a way to do so.

@Singleton
@Component(
    modules = [
        RepositoryModule::class,
    ]
)
interface TestAppComponent : AppComponent {

    @Component.Builder
    interface Builder : AppComponent.Builder {

        override fun build(): TestAppComponent
    }
}

The repository module

@Module
interface RepositoryModule {

    @Binds
    fun repository(repo: Repository): IRepository
}

And in my integration test :

class AppIntegTests {

    @Inject
    lateinit var repository: IRepository

    @BeforeTest
    fun setup() {
        repository.deleteAll()
    }

    @Test
    fun testRoot() {
        withTestApplication(config) {
            handleRequest { method = HttpMethod.Get; uri = "/users" }.apply {
               assertEquals(HttpStatusCode.OK, response.status())
            }
            // tests....
        }
    }
}

When doing this, I get lateinit property has not been initialized on my injected repository.
Is what I'm trying to do achievable with Dagger?

Body:
You have to pass reference of AppIntegTests class to dagger graph in order to initialize lateinit property by dagger

Add inject function to TestAppComponent

interface TestAppComponent  {

    fun inject(test: AppIntegTests)

    @Component.Builder
    interface Builder {
        fun build(): TestAppComponent
    }
}

call this method from setUp function of AppIntegTests

class AppIntegTests {

    @Inject
    lateinit var repository: IRepository

    @Before
    fun setup() {
        val testAppComponent = DaggerTestAppComponent.builder().build()
        testAppComponent.inject(this)

        repository.deleteAll()
    }


问:
While using AutoML from EvalML getting error AttributeError: 'DataTable' object has no attribute 'to_series'
I am running eval.automl on a data, made a class column as below:

```<code>df.loc[(df.quality<6), 'flag_class'] = 1
df.loc[(df.quality==6), 'flag_class'] = 2
df.loc[(df.quality>6), 'flag_class'] = 3
</code>```

then splitting it as below:

X = df[['several columns inside']].copy()
y = df[['flag_class']].copy()

but when running below code getting error:

X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, problem_type = 'multiclass')

error:

```<code>AttributeError                            Traceback (most recent call last)
<ipython-input-37-dffcb1214932> in <module>
----> 1 X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, problem_type = 'multiclass')

~\AppData\Roaming\Python\Python38\site-packages\evalml\preprocessing\utils.py in split_data(X, y,
problem_type, problem_configuration, test_size, random_seed)
     75         data_splitter = StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=random_seed)
     76
---> 77     train, test = next(data_splitter.split(X.to_dataframe(), y.to_series()))
     78
     79     X_train = X.iloc[train]

AttributeError: 'DataTable' object has no attribute 'to_series'
</code>```

Any support will be highly appreciated, Thanks in advance

答:
enter image description heredumie =y
type(dumie)
y_train=dumie.squeeze()
type(y_train)

Explanation: For dependent feature(y) should be series format DataTable can't convert it so First convert Y in to series by using squeeze
X should be in DataFrame format and Y should be series format

Body:
I am running eval.automl on a data, made a class column as below:

df.loc[(df.quality<6), 'flag_class'] = 1
df.loc[(df.quality==6), 'flag_class'] = 2
df.loc[(df.quality>6), 'flag_class'] = 3

then splitting it as below:

X = df[['several columns inside']].copy()
y = df[['flag_class']].copy()

but when running below code getting error:

X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, problem_type = 'multiclass')

error:

AttributeError                            Traceback (most recent call last)
<ipython-input-37-dffcb1214932> in <module>
----> 1 X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, problem_type = 'multiclass')

~\AppData\Roaming\Python\Python38\site-packages\evalml\preprocessing\utils.py in split_data(X, y,
problem_type, problem_configuration, test_size, random_seed)
     75         data_splitter = StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=random_seed)
     76
---> 77     train, test = next(data_splitter.split(X.to_dataframe(), y.to_series()))
     78
     79     X_train = X.iloc[train]

AttributeError: 'DataTable' object has no attribute 'to_series'

Any support will be highly appreciated, Thanks in advance


问:
Tomcat deploy context root via commandline
How can I deploy my war file at / via commandline? The following does not work:

```<code>curl -X PUT --upload-file ROOT.war "http://localhost:8080/manager/text/deploy?path=/" -u 'admin:password'
</code>```

It insteads gets deployed at /ROOT.war.

Thanks!

答: Everything is working as it is supposed to work: the base file name of the empty context path is ROOT (see naming scheme). Therefore a WAR file for the root context will be uploaded to $CATALINA_BASE/webapps/ROOT.war.

Body:
How can I deploy my war file at / via commandline? The following does not work:

curl -X PUT --upload-file ROOT.war "http://localhost:8080/manager/text/deploy?path=/" -u 'admin:password'

It insteads gets deployed at /ROOT.war.

Thanks!


问:
Remove Characters After Number
I have a string from a file which I need to remove all the characters after the substring "c1525". Can regex be used for this? The pattern I am seeing is that all my strings have a "c" then 4 digits (although I have seen more than 4 digits, so need to take that into consideration).

```<code>d098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566
</code>```

expected:

```<code>d098746532d1234567c1525
</code>```

答:
You could use a regex with a capturing group and re.sub:

```<code>import re

s = 'd098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566'

s2 = re.sub(r'(c\d{4,}).*', r'\1', s)
</code>```

output: 'd098746532d1234567c1525'

Title: Remove Characters After Number

Body:
I have a string from a file which I need to remove all the characters after the substring "c1525". Can regex be used for this? The pattern I am seeing is that all my strings have a "c" then 4 digits (although I have seen more than 4 digits, so need to take that into consideration).

d098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566

expected:

d098746532d1234567c1525

Body:
You could use a regex with a capturing group and re.sub:

import re

s = 'd098746532d1234567c1525qFPXplFSm-FS8575664637338586224hKwHFmFSRRnm0Uc006566'

s2 = re.sub(r'(c\d{4,}).*', r'\1', s)

output: 'd098746532d1234567c1525'


问:
Javascript Multiplying Within an Array
I have an array with multiple arrays inside.  I would like to multiply the contents of each array.

Here is my code--currently not getting anything in console.
The desired output is 3 numbers-- the result of multiplication of the three arrays

var arr = [
  [1, 2, 3],
  [3, 4],
  [7, 8, 9]
]
var mult = 1
for (i = 0; i < arr.length; i++) {
  for (j = 0; j < arr.length; j++) {
    mult *= arr[i][j]
  }
  console.log(mult)
}```

答:
One approach was to iterate the array of arrays via map which for each array puts the product of all of its items where the latter gets achieved via a multiplying reduce task.

console.log([

  [1, 2, 3],
  [3, 4],
  [7, 8, 9],

].map(arr =>
  arr.reduce((x, y) => x * y)
));```

Title: Javascript Multiplying Within an Array


问:
Axios + Multer Express req.file undefined
I'm trying to simply upload a single file from the client (react/axios) to the server (multer / express). I've read through every "req.file undefined" and can't seem to see the same issues with my own code.

The other issue is that actually my req on the server sees the file in the "files", but multer doesn't save it and req.file is undefined.

What could be happening here?

For client I've tried both methods of sending the form data, neither work.

    const onAnalyze = async () => {
        if (selectedFile !== null) {
            //we have a file, so that's what we're sending
            var formData = new FormData();
            formData.append("analyze", selectedFile);
            //let res = await api.post('/analyze/upload', formData)
            try {
                const response = await axios({
                    method: "post",
                    url: "http://localhost:5000/analyze/upload",
                    data: formData,
                    header: { "Content-Type": "multipart/form-data" }
                });
                console.log(response)
            } catch (error) {
                console.log(error)
            }
            // console.log(res)
            // setAnalysis(res.data)
        } else if (text.length <= maxLength) {
            let res = await api.post('/analyze', { text: text })
            setAnalysis(res.data)
        }
    }```
</div>
</div>
</p>
<p>For the server it seems simple.. I just don't know. This file destination exists. req.file is always undefined
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import express from 'express';
import { getMedia, createMedia } from '../controllers/media.js';
import { AnalyzeText, AnalyzeFile } from '../controllers/analyze.js'
import multer from 'multer'

const fileStorageEngine = multer.diskStorage({
    destination: "uploads",
    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
});

var upload = multer({ storage: fileStorageEngine })

const router = express.Router();

//Get All Movies and TV shows.
router.get('/', getMedia);

//Request to create a new item based on a title
router.post('/', createMedia);

//Recuist to analyze information (not sure if this should be a post or not)
router.post('/analyze', AnalyzeText)

router.post('/analyze/upload', upload.single('analyze'), (req, res) => {
    console.log(req.file)
    res.status(200).json('well we found it again');
});</code>```

答: Turns out I had another middleware running that was wrapping my file upload. Removed that, everything works.</p>

Body:
I'm trying to simply upload a single file from the client (react/axios) to the server (multer / express). I've read through every "req.file undefined" and can't seem to see the same issues with my own code.

The other issue is that actually my req on the server sees the file in the "files", but multer doesn't save it and req.file is undefined.

What could be happening here?

For client I've tried both methods of sending the form data, neither work.

    const onAnalyze = async () => {
        if (selectedFile !== null) {
            //we have a file, so that's what we're sending
            var formData = new FormData();
            formData.append("analyze", selectedFile);
            //let res = await api.post('/analyze/upload', formData)
            try {
                const response = await axios({
                    method: "post",
                    url: "http://localhost:5000/analyze/upload",
                    data: formData,
                    header: { "Content-Type": "multipart/form-data" }
                });
                console.log(response)
            } catch (error) {
                console.log(error)
            }
            // console.log(res)
            // setAnalysis(res.data)
        } else if (text.length <= maxLength) {
            let res = await api.post('/analyze', { text: text })
            setAnalysis(res.data)
        }
    }

For the server it seems simple.. I just don't know. This file destination exists. req.file is always undefined

import express from 'express';
import { getMedia, createMedia } from '../controllers/media.js';
import { AnalyzeText, AnalyzeFile } from '../controllers/analyze.js'
import multer from 'multer'

const fileStorageEngine = multer.diskStorage({
    destination: "uploads",
    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
});

var upload = multer({ storage: fileStorageEngine })

const router = express.Router();

//Get All Movies and TV shows.
router.get('/', getMedia);

//Request to create a new item based on a title
router.post('/', createMedia);

//Recuist to analyze information (not sure if this should be a post or not)
router.post('/analyze', AnalyzeText)

router.post('/analyze/upload', upload.single('analyze'), (req, res) => {
    console.log(req.file)
    res.status(200).json('well we found it again');
});