问:
Facelets welcome page not found or redirected using Spring Boot
I am currently trying to move a java EE 8 project running on wildfly to the latest spring boot.

For this i will need primefaces, primefaces-extensions and omnifaces cause of it's
components i am already using and also designed (buyed) theme.

Starting with the latest spring boot in combination with joinfaces i currently try to
define the welcome page or redirect to the index.xhtml page
but anything i tried failed.

Here is my current sources:

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<!-- Project settings -->
<groupId>com.skf.ecocalcweb</groupId>
<artifactId>EcoCalcDD4Web</artifactId>
<version>2.0.0</version>
<packaging>jar</packaging>

<!-- Using spring boot as parent -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<!-- Project properties -->
<properties>
    <!-- General settings -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <java.version>1.8</java.version>
    <!-- Libraries versions -->
    <lombok.version>1.18.12</lombok.version>
    <joinfaces.version>4.1.4</joinfaces.version>
    <primefaces.core.version>7.0.11</primefaces.core.version>
    <primefaces.extensions.version>7.0.3</primefaces.extensions.version>
    <omnifaces.version>3.4.1</omnifaces.version>
    <fontawesome.version>5.12.0</fontawesome.version>
</properties>

<!-- Use joinfaces for jsf starters -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.joinfaces</groupId>
            <artifactId>joinfaces-dependencies</artifactId>
            <version>${joinfaces.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<!-- JAR-Dependencies -->
<dependencies>
    <!-- Spring boot starters -->
    <!-- Exclude mojarra, so use myfaces instead -->
    <dependency>
        <groupId>org.joinfaces</groupId>
        <artifactId>primefaces-spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.joinfaces</groupId>
                <artifactId>mojarra-spring-boot-starter</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.joinfaces</groupId>
        <artifactId>myfaces-spring-boot-starter</artifactId>
    </dependency>
    <!-- Also use omnifaces3, so latest jsf version must be used -->
    <dependency>
        <groupId>org.joinfaces</groupId>
        <artifactId>omnifaces3-spring-boot-starter</artifactId>
    </dependency>
    <!-- Java Enterprise API for using primefaces in JSF -->
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- OmniFaces -->
    <dependency>
        <groupId>org.omnifaces</groupId>
        <artifactId>omnifaces</artifactId>
        <version>${omnifaces.version}</version>
    </dependency>
    <!-- Primefaces core -->
    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>${primefaces.core.version}-SNAPSHOT</version>
    </dependency>
    <!-- Primefaces extensions -->
    <dependency>
        <groupId>org.primefaces.extensions</groupId>
        <artifactId>primefaces-extensions</artifactId>
        <version>${primefaces.extensions.version}</version>
    </dependency>
    <!-- Primefaces theme -->
    <dependency>
        <groupId>com.skf.ecocalcweb</groupId>
        <artifactId>PrimefacesTheme</artifactId>
        <version>1.0.0</version>
    </dependency>
    <!-- Font Awesome -->
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>font-awesome</artifactId>
        <version>${fontawesome.version}</version>
    </dependency>
    <!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<!-- Package as an executable jar -->
<build>
    <!-- Final name of war-file -->
    <finalName>${project.artifactId}</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

/src/main/java/com/test/Application.java

```<code>    @SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(Application.class);
    app.run(args);
  }

  @Bean
  public ServletRegistrationBean facesServletRegistration() {
    FacesServlet servlet = new FacesServlet();
    ServletRegistrationBean registration = new ServletRegistrationBean(servlet, new String[]{"*.xhtml"});
    registration.setName("Faces Servlet");
    registration.setLoadOnStartup(1);
    registration.setEnabled(true);
    registration.setOrder(1);
    return registration;
  }

  @Bean
  public ServletContextInitializer servletContextInitializer() {
    return servletContext -> {
      // MyFaces
      servletContext.setInitParameter("org.apache.myfaces.LOG_WEB_CONTEXT_PARAMS", Boolean.FALSE.toString());
      // Primefaces
      servletContext.setInitParameter("primefaces.THEME", "harmony-fate");
      servletContext.setInitParameter("primefaces.MOVE_SCRIPTS_TO_BOTTOM", Boolean.FALSE.toString());
      servletContext.setInitParameter("primefaces.FONT_AWESOME", Boolean.TRUE.toString());
      // Omnifaces
      servletContext.setInitParameter("org.omnifaces.SOCKET_ENDPOINT_ENABLED", Boolean.TRUE.toString());
      // JavaX
      servletContext.setInitParameter("javax.faces.PROJECT_STAGE", "Production");
      servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
      servletContext.setInitParameter("com.sun.faces.enableRestoreView11Compatibility", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.STATE_SAVING_METHOD", "server");
      servletContext.setInitParameter("com.sun.faces.compressViewState", Boolean.FALSE.toString());
      servletContext.setInitParameter("com.sun.face.serializeServerState", Boolean.FALSE.toString());
      servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "-1");
      servletContext.setInitParameter("javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.ENABLE_CDI_RESOLVER_CHAIN", Boolean.TRUE.toString());
    };
  }
}
</code>```

/src/main/java/com/test/controllers/Index.java

```<code>@Getter
@Setter
@RequestScope
@Named
public class Index {

  private String firstName = "John";
  private String lastName = "Doe";

  public String showGreeting() {
    return "Hello " + firstName + " " + lastName + "!";
  }
}
</code>```

/src/main/resources/META-INF/resources/index.xhtml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:p="http://primefaces.org/ui">

<h:head>
  <title>PrimeFaces Hello World Example</title>
</h:head>

<h:body>
  <h:form id="helloworld-form">

    <p:panel header="PrimeFaces Hello World Example">
      <h:panelGrid columns="2" cellpadding="4">
        <h:outputText value="First Name: " />
        <p:inputText id="first-name" value="#{index.firstName}" />

        <h:outputText value="Last Name: " />
        <p:inputText id="last-name" value="#{index.lastName}" />

        <p:commandButton id="submit" value="Submit"
          update="greeting-panel"
          oncomplete="PF('greetingDialog').show()" />
      </h:panelGrid>
    </p:panel>

    <p:dialog header="Greeting" widgetVar="greetingDialog"
      modal="true" resizable="false">
      <h:panelGrid id="greeting-panel" columns="1" cellpadding="4">
        <h:outputText value="#{index.showGreeting()}" />
      </h:panelGrid>
    </p:dialog>

  </h:form>
</h:body>
</html>
</code>```

/src/main/resources/META-INF/resources/application.properties

```<code># the embedded application server config
server.port=80
server.servlet.context-path=/

# thymeleaf templating engine config
spring.thymeleaf.enabled=false
</code>```

So what's needed here to set the welcome-page for a jsf application right ?

When i directly called
http://localhost/index.xhtml
the primefaces page will be rendered right,
but when i enter
http://localhost/
no redirect to the index.xhtml will be made
and i currently found nothing which is working as a "redirect" ...

答:
I think i currently found the solution :

So i post it for all others which are start using spring boot and primefaces together:

Adding this dependency will fix my problem with the welcome page as xhtml :

```<code><!-- Add spring boot web needed for navigation -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
</code>```

Then i can use the following class file to set my welcome-page:

/src/main/java/com/test/navigation/WelcomePageRedirect.java

```<code>@Configuration
public class WelcomePageRedirect implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/")
                .setViewName("forward:/index.xhtml");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}
</code>```

Now the following technologies are working together:

Java 8 (And also Java 11 !)

Primefaces 7.0.11 + Primefaces Extensions

Omnifaces 3.4.1

Latest FontAwesome 5.12.0 in combination with Primefaces "old" FontAwesome

Spring Boot 2.2.4

JoinFaces 4.1.4

MyFaces 2.3

Body:
I am currently trying to move a java EE 8 project running on wildfly to the latest spring boot.

For this i will need primefaces, primefaces-extensions and omnifaces cause of it's
components i am already using and also designed (buyed) theme.

Starting with the latest spring boot in combination with joinfaces i currently try to
define the welcome page or redirect to the index.xhtml page
but anything i tried failed.

Here is my current sources:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.skf.ecocalcweb</groupId>
<artifactId>EcoCalcDD4Web</artifactId>
<version>2.0.0</version>
<packaging>jar</packaging>

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

<properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <java.version>1.8</java.version>

    <lombok.version>1.18.12</lombok.version>
    <joinfaces.version>4.1.4</joinfaces.version>
    <primefaces.core.version>7.0.11</primefaces.core.version>
    <primefaces.extensions.version>7.0.3</primefaces.extensions.version>
    <omnifaces.version>3.4.1</omnifaces.version>
    <fontawesome.version>5.12.0</fontawesome.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.joinfaces</groupId>
            <artifactId>joinfaces-dependencies</artifactId>
            <version>${joinfaces.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>

    <dependency>
        <groupId>org.joinfaces</groupId>
        <artifactId>primefaces-spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.joinfaces</groupId>
                <artifactId>mojarra-spring-boot-starter</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.joinfaces</groupId>
        <artifactId>myfaces-spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.joinfaces</groupId>
        <artifactId>omnifaces3-spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>org.omnifaces</groupId>
        <artifactId>omnifaces</artifactId>
        <version>${omnifaces.version}</version>
    </dependency>

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>${primefaces.core.version}-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>org.primefaces.extensions</groupId>
        <artifactId>primefaces-extensions</artifactId>
        <version>${primefaces.extensions.version}</version>
    </dependency>

    <dependency>
        <groupId>com.skf.ecocalcweb</groupId>
        <artifactId>PrimefacesTheme</artifactId>
        <version>1.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>font-awesome</artifactId>
        <version>${fontawesome.version}</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<build>

    <finalName>${project.artifactId}</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

/src/main/java/com/test/Application.java

    @SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(Application.class);
    app.run(args);
  }

  @Bean
  public ServletRegistrationBean facesServletRegistration() {
    FacesServlet servlet = new FacesServlet();
    ServletRegistrationBean registration = new ServletRegistrationBean(servlet, new String[]{"*.xhtml"});
    registration.setName("Faces Servlet");
    registration.setLoadOnStartup(1);
    registration.setEnabled(true);
    registration.setOrder(1);
    return registration;
  }

  @Bean
  public ServletContextInitializer servletContextInitializer() {
    return servletContext -> {
      // MyFaces
      servletContext.setInitParameter("org.apache.myfaces.LOG_WEB_CONTEXT_PARAMS", Boolean.FALSE.toString());
      // Primefaces
      servletContext.setInitParameter("primefaces.THEME", "harmony-fate");
      servletContext.setInitParameter("primefaces.MOVE_SCRIPTS_TO_BOTTOM", Boolean.FALSE.toString());
      servletContext.setInitParameter("primefaces.FONT_AWESOME", Boolean.TRUE.toString());
      // Omnifaces
      servletContext.setInitParameter("org.omnifaces.SOCKET_ENDPOINT_ENABLED", Boolean.TRUE.toString());
      // JavaX
      servletContext.setInitParameter("javax.faces.PROJECT_STAGE", "Production");
      servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
      servletContext.setInitParameter("com.sun.faces.enableRestoreView11Compatibility", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.STATE_SAVING_METHOD", "server");
      servletContext.setInitParameter("com.sun.faces.compressViewState", Boolean.FALSE.toString());
      servletContext.setInitParameter("com.sun.face.serializeServerState", Boolean.FALSE.toString());
      servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "-1");
      servletContext.setInitParameter("javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE", Boolean.TRUE.toString());
      servletContext.setInitParameter("javax.faces.ENABLE_CDI_RESOLVER_CHAIN", Boolean.TRUE.toString());
    };
  }
}

/src/main/java/com/test/controllers/Index.java

@Getter
@Setter
@RequestScope
@Named
public class Index {

  private String firstName = "John";
  private String lastName = "Doe";

  public String showGreeting() {
    return "Hello " + firstName + " " + lastName + "!";
  }
}

/src/main/resources/META-INF/resources/index.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
  <title>PrimeFaces Hello World Example</title>
</h:head>

<h:body>
  <h:form id="helloworld-form">

      <h:panelGrid columns="2" cellpadding="4">
        <h:outputText value="First Name: " />

        <h:outputText value="Last Name: " />

      </h:panelGrid>

      <h:panelGrid id="greeting-panel" columns="1" cellpadding="4">
        <h:outputText value="#{index.showGreeting()}" />
      </h:panelGrid>

  </h:form>
</h:body>

/src/main/resources/META-INF/resources/application.properties

# the embedded application server config
server.port=80
server.servlet.context-path=/

# thymeleaf templating engine config
spring.thymeleaf.enabled=false

So what's needed here to set the welcome-page for a jsf application right ?

When i directly called
http://localhost/index.xhtml
the primefaces page will be rendered right,
but when i enter
http://localhost/
no redirect to the index.xhtml will be made
and i currently found nothing which is working as a "redirect" ...

Body:
I think i currently found the solution :

So i post it for all others which are start using spring boot and primefaces together:

Adding this dependency will fix my problem with the welcome page as xhtml :

<!-- Add spring boot web needed for navigation -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Then i can use the following class file to set my welcome-page:

/src/main/java/com/test/navigation/WelcomePageRedirect.java

@Configuration
public class WelcomePageRedirect implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/")
                .setViewName("forward:/index.xhtml");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}

Now the following technologies are working together:

Java 8 (And also Java 11 !)

Primefaces 7.0.11 + Primefaces Extensions

Omnifaces 3.4.1

Latest FontAwesome 5.12.0 in combination with Primefaces "old" FontAwesome

Spring Boot 2.2.4

JoinFaces 4.1.4

MyFaces 2.3


来源: stackexchange

问:
How to merge interfaces from NPM modules correctly in TypeScript?
The @types/yandex-maps package contains namespace ymaps.

It has interface IEventManager.

I want to add a new method to this interface IEventManager.

I'm trying to do this in my file .d.ts:

```<code>import {IEvent} from '@types/yandex-maps';

declare module '@types/yandex-maps' {
    declare namespace ymaps {
        interface IEventManager {
            once(types: string[][] | string[] | string, callback: (event: object | IEvent) => void, context?: object, priority?: number): this;
        }
    }
}
</code>```

But it doesn't work! How do I add the method I need correctly?

答:
```<code>
import {IEvent} from '@types/yandex-maps';

declare module '@types/yandex-maps' {
    declare namespace ymaps {
        interface IEventManager {
            once(types: string[][] | string[] | string, callback: (event: object | IEvent) => void, context?: object, priority?: number): this;
        }
    }
    export = ymaps;
    export as namespace ymaps;
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
The @types/yandex-maps package contains namespace ymaps.

It has interface IEventManager.

I want to add a new method to this interface IEventManager.

I'm trying to do this in my file .d.ts:

import {IEvent} from '@types/yandex-maps';

declare module '@types/yandex-maps' {
    declare namespace ymaps {
        interface IEventManager {
            once(types: string[][] | string[] | string, callback: (event: object | IEvent) => void, context?: object, priority?: number): this;
        }
    }
}

But it doesn't work! How do I add the method I need correctly?


问:
Delete collection firestore:go
I took a data set of 10 collections from api xyz, then updated it to firebase for the first time.

On the second update, api xyz has 9 collections available, How to make the 2nd update with only 9 collections (the existing ones being overwritten and the extra collections from the first update should be deleted)?

I used to delete all the collections and then update but that method is not appropriate.

答:
For you to perform bulk updates on your collections, you need to use
Transactions and Batched Writes - as I imagine that you are already using to perform the update in the first time.

If you just want to overwrite the old date, you need to configure a set() method just to update the collection, without needing to check the existence of any document on it. This way, it should overwrite the data already existed. You can get more information on this question here, where a customer describes the function that he is using that is overwriting data.

Let me know if the information helped you!

Title: Delete collection firestore:go


问:
Yaml content parsing and making list from it - went wrong (python 3.x)
I try to make an input for plots. I have yaml files with some content (as year, resolution...) and I want to do a list, which would contain "years" from all of my desired yaml files and then I will use it later as input for plots.

The list should look like that: [2010, 2011, 2013,...]

But my code gives me this list:

[2014]

[2014, 2015]

[2014, 2015, 2015]

I assume that problem is somewhere in "for" cycles?

Here is the code:

```<code>import glob
import yaml

pdb_codes = ['3J7Z', '3J9Y', '3J9Z', '3JA1', '3JBU', '3JBV'] #just example of few, there are many more
years = []

for codes in pdb_codes:
    # get directories
    directories = glob.glob("../../../../DATA/{}/" .format(codes))

    # sort directories because the glob method yields them unordered
    directories_sorted = sorted(directories)

    # browse directories
    for directory in directories_sorted:
        pdb_code = directory.split("/")[-2]
        yaml_name = directory + pdb_code + ".yaml"

        with open(yaml_name) as stream:
            yaml_content = yaml.load(stream, Loader=yaml.FullLoader)
            year = yaml_content["Year"]
            years.append(year)

    print(years)
</code>```

答:
Based on the code, my understanding is that there is only ONE yaml file in every directory, which you are reading and appending the year to the years list. As you are printing after each directory, only one year appending and the list is getting printed.
Try printing the list after the outer loop.

Sorry if I did not understand the question properly.

Body:
I try to make an input for plots. I have yaml files with some content (as year, resolution...) and I want to do a list, which would contain "years" from all of my desired yaml files and then I will use it later as input for plots.

The list should look like that: [2010, 2011, 2013,...]

But my code gives me this list:

[2014]

[2014, 2015]

[2014, 2015, 2015]

I assume that problem is somewhere in "for" cycles?

Here is the code:

import glob
import yaml

pdb_codes = ['3J7Z', '3J9Y', '3J9Z', '3JA1', '3JBU', '3JBV'] #just example of few, there are many more
years = []

for codes in pdb_codes:
    # get directories
    directories = glob.glob("../../../../DATA/{}/" .format(codes))

    # sort directories because the glob method yields them unordered
    directories_sorted = sorted(directories)

    # browse directories
    for directory in directories_sorted:
        pdb_code = directory.split("/")[-2]
        yaml_name = directory + pdb_code + ".yaml"

        with open(yaml_name) as stream:
            yaml_content = yaml.load(stream, Loader=yaml.FullLoader)
            year = yaml_content["Year"]
            years.append(year)

    print(years)


问:
How do I find the duplicates in a list and create another list with them?
How do I find the duplicates in a list of integers and create another list of the duplicates?</p>

答:
Using Set Function
eg:-

```<code>arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr2=list(set(arr))
print(arr2)
</code>```

Output:- [1, 2, 3, 4, 5]

Remove Duplicates using array

eg:-

```<code>arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr3=[]
for i in arr:
    if(i not in arr3):
     arr3.append(i)
print(arr3)
</code>```

Output:-

[1, 4, 2, 5, 3]

Using Lambda Function

eg:-

```<code>rem_duplicate_func=lambda arr:set(arr)
print(rem_duplicate_func(arr))
</code>```

Output:-

{1, 2, 3, 4, 5}

Remove Duplicate Values from dictionary

eg:-

```<code>dict1={
    'car':["Ford","Toyota","Ford","Toyota"],
    'brand':["Mustang","Ranz","Mustang","Ranz"] } dict2={} for key,value in dict1.items():
    dict2[key]=set(value) print(dict2)
</code>```

Output:-

{'car': {'Toyota', 'Ford'}, 'brand': {'Ranz', 'Mustang'}}

Symmetric difference- Remove duplicate elements

eg:-

```<code>set1={1,2,4,5}
set2={2,1,5,7}
rem_dup_ele=set1.symmetric_difference(set2)
print(rem_dup_ele)
</code>```

Output:-

{4, 7}

Body:
Using Set Function
eg:-

arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr2=list(set(arr))
print(arr2)

Output:- [1, 2, 3, 4, 5]

Remove Duplicates using array

eg:-

arr=[1,4,2,5,2,3,4,1,4,5,2,3]
arr3=[]
for i in arr:
    if(i not in arr3):
     arr3.append(i)
print(arr3)

Output:-

[1, 4, 2, 5, 3]

Using Lambda Function

eg:-

rem_duplicate_func=lambda arr:set(arr)
print(rem_duplicate_func(arr))

Output:-

{1, 2, 3, 4, 5}

Remove Duplicate Values from dictionary

eg:-

dict1={
    'car':["Ford","Toyota","Ford","Toyota"],
    'brand':["Mustang","Ranz","Mustang","Ranz"] } dict2={} for key,value in dict1.items():
    dict2[key]=set(value) print(dict2)

Output:-

{'car': {'Toyota', 'Ford'}, 'brand': {'Ranz', 'Mustang'}}

Symmetric difference- Remove duplicate elements

eg:-

set1={1,2,4,5}
set2={2,1,5,7}
rem_dup_ele=set1.symmetric_difference(set2)
print(rem_dup_ele)

Output:-

{4, 7}


问:
How to get an array of character (A-z, no numbers) from a given string?
I need a java regex to answer my question.

this is my code:

```<code>char[] array = s.split("regex");
</code>```

答:
First replace non-letter characters with blank space, then convert String to char array:</p>

```<code>char[] onlyLetters = "regex".replaceAll("[^A-Za-z]+", "").toCharArray();
</code>```

Body:
I need a java regex to answer my question.

this is my code:

char[] array = s.split("regex");

Body:
First replace non-letter characters with blank space, then convert String to char array:

char[] onlyLetters = "regex".replaceAll("[^A-Za-z]+", "").toCharArray();


问:
How can I make my reg exp less greedy?
I'm trying select a small porting of the XML below but my reg exp doesn't work as expected.

My reg exp

```<code><w:p [^<>]*><w:r><w:t>\[end participant\]<\/w:t><\/w:r><\/w:p>
</code>```

It should match

```<code><w:p w:rsidRDefault="009C141F" w:rsidP="006003BD">
  <w:pPr>
    <w:spacing w:after="240" />
  </w:pPr>
  <w:r>
    <w:t>[end participant]</w:t>
  </w:r>
</w:p>
</code>```

But it matches up to the first w:p tag.

Here is the complete XML

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml">
  <w:body>
    <w:p w:rsidRDefault="001660DB" w:rsidP="001660DB">
      <w:pPr>
        <w:pStyle w:val="Titre1" />
        <w:spacing w:before="0" />
      </w:pPr>
      <w:r>
        <w:t>Salut</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="001660DB" w:rsidP="001660DB">
      <w:pPr>
        <w:pStyle w:val="Titre2" />
        <w:spacing w:before="0" />
      </w:pPr>
      <w:r>
        <w:t>Hello les gens &àè!</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="00F87349" />
    <w:p w:rsidRDefault="009C141F">
      <w:r>
        <w:t>[start participant]</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="009C141F" w:rsidP="006003BD">
      <w:pPr>
        <w:pStyle w:val="Titre1" />
        <w:spacing w:before="0" w:after="240" />
      </w:pPr>
      <w:r>
        <w:t xml:space="preserve">Mr #NOM# #PRENOM#</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="009C141F" w:rsidP="006003BD">
      <w:pPr>
        <w:spacing w:after="240" />
      </w:pPr>
      <w:r>
        <w:t>[end participant]</w:t>
      </w:r>
    </w:p>
    <w:sectPr w:rsidSect="00425138">
      <w:pgSz w:w="11906" w:h="16838" />
      <w:pgMar w:top="1417" w:right="1417" w:bottom="1417" w:left="1417" w:header="708" w:footer="708" w:gutter="0" />
      <w:cols w:space="708" />
      <w:docGrid w:linePitch="360" />
    </w:sectPr>
  </w:body>
</w:document>
</code>```

thanks

答:
I think you're missing the tag for spacing:

```<code><w:p [^<>]*><w:pPr><w:spacing [^<>]*/></w:pPr><w:r><w:t>\[end participant\]<\/w:t><\/w:r><\/w:p>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can I make my reg exp less greedy?

Body:
I'm trying select a small porting of the XML below but my reg exp doesn't work as expected.

My reg exp

<w:p [^<>]*><w:r><w:t>\[end participant\]<\/w:t><\/w:r><\/w:p>

It should match

<w:p w:rsidRDefault="009C141F" w:rsidP="006003BD">
  <w:pPr>
    <w:spacing w:after="240" />
  </w:pPr>
  <w:r>
    <w:t>[end participant]</w:t>
  </w:r>
</w:p>

But it matches up to the first w:p tag.

Here is the complete XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml">
  <w:body>
    <w:p w:rsidRDefault="001660DB" w:rsidP="001660DB">
      <w:pPr>
        <w:pStyle w:val="Titre1" />
        <w:spacing w:before="0" />
      </w:pPr>
      <w:r>
        <w:t>Salut</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="001660DB" w:rsidP="001660DB">
      <w:pPr>
        <w:pStyle w:val="Titre2" />
        <w:spacing w:before="0" />
      </w:pPr>
      <w:r>
        <w:t>Hello les gens &àè!</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="00F87349" />
    <w:p w:rsidRDefault="009C141F">
      <w:r>
        <w:t>[start participant]</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="009C141F" w:rsidP="006003BD">
      <w:pPr>
        <w:pStyle w:val="Titre1" />
        <w:spacing w:before="0" w:after="240" />
      </w:pPr>
      <w:r>
        <w:t xml:space="preserve">Mr #NOM# #PRENOM#</w:t>
      </w:r>
    </w:p>
    <w:p w:rsidRDefault="009C141F" w:rsidP="006003BD">
      <w:pPr>
        <w:spacing w:after="240" />
      </w:pPr>
      <w:r>
        <w:t>[end participant]</w:t>
      </w:r>
    </w:p>
    <w:sectPr w:rsidSect="00425138">
      <w:pgSz w:w="11906" w:h="16838" />
      <w:pgMar w:top="1417" w:right="1417" w:bottom="1417" w:left="1417" w:header="708" w:footer="708" w:gutter="0" />
      <w:cols w:space="708" />
      <w:docGrid w:linePitch="360" />
    </w:sectPr>
  </w:body>
</w:document>

thanks

Body:
I think you're missing the tag for spacing:

<w:p [^<>]*><w:pPr><w:spacing [^<>]*/></w:pPr><w:r><w:t>\[end participant\]<\/w:t><\/w:r><\/w:p>


问:
Voyager for Laravel 5: Wrong paths for images
Having created a new user via Voyager, the avatar was showing as a broken image. I uploaded a new image, but the image remained broken.

I checked with Console in Google Chrome and found 3 404 errors:

2017-06-19 10:53:50.159
  http://localhost:8888/storage/users/June2017/ypKlbqbATDbpnYctZBFp.png
  Failed to load resource: the server responded with a status of 404
  (Not Found)

2017-06-19 10:53:50.256
  http://localhost:8888/storage/users/June2017/ypKlbqbATDbpnYctZBFp.png
  Failed to load resource: the server responded with a status of 404
  (Not Found)

2017-06-19 10:53:50.473
  http://localhost:8888/vendor/tcg/voyager/assets/images/bg.jpg Failed
  to load resource: the server responded with a status of 404 (Not
  Found) When I looked at the project, the paths for the 2 storage
  errors are: http://localhost:8888/storage/app/public/users/ and:
  http://localhost:8888/storage/app/public/users/June2017

While in Media, I'm seeing similar path problems when navigating the folders:

2017-06-19 11:38:22.248 %7B%7B%20selected_file.path%20%7D%7D:1 GET
  http://localhost:8888/development/PhpstormProjects/Search4Venues/public/admin/%7B%7B%20selected_file.path%20%7D%7D
  404 (Not Found)

Anticipating the question, in .env, I have: APP_URL=http://localhost:8888

Is this a configuration error?

EDIT

A colleague with more experience than me has been through Voyager and found some inconsistencies, which he's attempted to fix.

In app.php, we've had to change:

```<code>'url' => env('APP_URL', 'http://localhost:8888/development/PhpstormProjects/Search4Venues'),
</code>```

... to:

```<code>'url' => env('APP_URL', 'http://localhost:8888'),
</code>```

In filesystems.php, we've had to change:

```<code>'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
]
</code>```

... to:

```<code>'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/development/PhpstormProjects/Search4Venues/public/storage',
    'visibility' => 'public',
]
</code>```

However, he discovered other problems in config/voyager.php:

```<code>'assets_path' => '/vendor/tcg/voyager/assets',
</code>```

... where it too appears to be missing PhpstormProjects/Search4Venues from the path:

```<code>http://localhost:8888/vendor/tcg/voyager/assets/images/bg.jpg
</code>```

At this stage, we have no idea what else could be wrong with Voyager.

答:
Change one line in .env file:

```<code>APP_URL = http://localhost
</code>```

to

```<code>APP_URL = http://<your site url>
</code>```

The command is used to remove the configuration cache file and created again.

```<code>php artisan config:cache
</code>```

Body:
Having created a new user via Voyager, the avatar was showing as a broken image. I uploaded a new image, but the image remained broken.

I checked with Console in Google Chrome and found 3 404 errors:

2017-06-19 10:53:50.159
  http://localhost:8888/storage/users/June2017/ypKlbqbATDbpnYctZBFp.png
  Failed to load resource: the server responded with a status of 404
  (Not Found)

2017-06-19 10:53:50.256
  http://localhost:8888/storage/users/June2017/ypKlbqbATDbpnYctZBFp.png
  Failed to load resource: the server responded with a status of 404
  (Not Found)

2017-06-19 10:53:50.473
  http://localhost:8888/vendor/tcg/voyager/assets/images/bg.jpg Failed
  to load resource: the server responded with a status of 404 (Not
  Found) When I looked at the project, the paths for the 2 storage
  errors are: http://localhost:8888/storage/app/public/users/ and:
  http://localhost:8888/storage/app/public/users/June2017

While in Media, I'm seeing similar path problems when navigating the folders:

2017-06-19 11:38:22.248 %7B%7B%20selected_file.path%20%7D%7D:1 GET
  http://localhost:8888/development/PhpstormProjects/Search4Venues/public/admin/%7B%7B%20selected_file.path%20%7D%7D
  404 (Not Found)

Anticipating the question, in .env, I have: APP_URL=http://localhost:8888

Is this a configuration error?

EDIT

A colleague with more experience than me has been through Voyager and found some inconsistencies, which he's attempted to fix.

In app.php, we've had to change:

'url' => env('APP_URL', 'http://localhost:8888/development/PhpstormProjects/Search4Venues'),

... to:

'url' => env('APP_URL', 'http://localhost:8888'),

In filesystems.php, we've had to change:

'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
]

... to:

'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/development/PhpstormProjects/Search4Venues/public/storage',
    'visibility' => 'public',
]

However, he discovered other problems in config/voyager.php:

'assets_path' => '/vendor/tcg/voyager/assets',

... where it too appears to be missing PhpstormProjects/Search4Venues from the path:

http://localhost:8888/vendor/tcg/voyager/assets/images/bg.jpg

At this stage, we have no idea what else could be wrong with Voyager.

Body:
Change one line in .env file:

APP_URL = http://localhost

to

APP_URL = http://<your site url>

The command is used to remove the configuration cache file and created again.

php artisan config:cache


问:
How to handle "Error in render: TypeError: Cannot read property 'abc' of undefined" in Vue js
Real-world data is often not as structured as we think. I remember if an angularjs template tries to access a property of undefined, it just renders an empty string. I like this default very much. When it comes to Vue, a single error will prevent the whole component from rendering.

I read about error boundary but it is unrealistic to wrap every single element that might access a property of undefined.

My question is: how to gracefully handle such errors and confidently build a component that always renders, even with bad data?

答:
You can use something like this:

```<code><p>{{x?x.abc:""}}</p>
</code>```

if x in not defined in your data object, this will raise a warring but your app will still functioning ok.

One way to work around this warring, is to define a getter like for x in your computed object, something like this:

```<code>{
  data(){
    _x:null, //or it may completely missing or an empty object {}
  },
  computed:{
    x: function(){
      return this._x?this._x:{}
    }
  }
}
</code>```

now you can use it like:

```<code><p>{{x.abc}}</p>
</code>```

Body:
You can use something like this:

<p>{{x?x.abc:""}}</p>

if x in not defined in your data object, this will raise a warring but your app will still functioning ok.

One way to work around this warring, is to define a getter like for x in your computed object, something like this:

{
  data(){
    _x:null, //or it may completely missing or an empty object {}
  },
  computed:{
    x: function(){
      return this._x?this._x:{}
    }
  }
}

now you can use it like:

<p>{{x.abc}}</p>


问:
Pythonic way to iterate through the input which can be a string, list or dict
I'm new to programming and have a requirement wherein I have to iterate through the elements of an input. The input can be a string, a list (mostly) or a dict. I wrote some code to check if the given input is a string or a list or a dict etc., but I'm wondering if there is an easier way to do it.

For example, I check as follows:

```<code> if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 if isinstance(vlan, string):
      <<do some operation here>>
 if isinstance(vlan, dict):
      for i in vlan.keys()
         <<do some operation here>>
</code>```

This operation I have to carry out a lot of times (although I can write a function do expand and send the elements I'm just wondering if there is any alternate to it).

答:
Use elif instead of if:

```<code> if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 elif isinstance(vlan, str):
      <<do some operation here>>
 elif isinstance(vlan, dict):
      for i in vlan.keys():
         <<do some operation here>>
</code>```

Body:
I'm new to programming and have a requirement wherein I have to iterate through the elements of an input. The input can be a string, a list (mostly) or a dict. I wrote some code to check if the given input is a string or a list or a dict etc., but I'm wondering if there is an easier way to do it.

For example, I check as follows:

 if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 if isinstance(vlan, string):
      <<do some operation here>>
 if isinstance(vlan, dict):
      for i in vlan.keys()
         <<do some operation here>>

This operation I have to carry out a lot of times (although I can write a function do expand and send the elements I'm just wondering if there is any alternate to it).

Body:
Use elif instead of if:

 if isinstance(vlan, list):
      for i in  vlan:
          <<do some operation here>>
 elif isinstance(vlan, str):
      <<do some operation here>>
 elif isinstance(vlan, dict):
      for i in vlan.keys():
         <<do some operation here>>


问:
STM32L1 - Malloc issue (Beginner Question)
I'm kinda new to C but feel I have a good basic understanding and hence have posted the question here.

I am trying to port over some demo code for a Waveshare E-paper display to use for an application in my Graduate Project. For now I just wanted to prove the demo code works but will most likely use aspects of it later on.

The issue I am currently having is with use of the following lines:

```<code>// Create a new image cache
UBYTE *BlackImage;
UWORD Imagesize = ((EPD_WIDTH % 8 == 0)? (EPD_WIDTH / 8 ): (EPD_WIDTH / 8 + 1)) * EPD_HEIGHT;
if((BlackImage = (UBYTE *)malloc(Imagesize)) == NULL)
    {
    printf("Failed to apply for memory...\r\n");
    return -1;
}
</code>```

I am pretty sure my understanding of this is correct, but the essentially:

A pointer is created for BlackImage

The size of memory to be allocated for Blackimage is decided based of the display dimensions

In the if statement, BlackImage is assigned the memory size from the above line, and rerturns the pointer value for BlackImage. If this pointer value is NULL (i.e. 0) then the memory has not been allocated.

My code is always failing at 'applying this memory'. I assume the reasons are that I do not have enough memory available.. but here are my questions:

If I do not have enough memory - where do I look to find this out? (I am using Keil uVision IDE)

Can I solve this by shifting memory allocations round? Does malloc store in a specific type of memory? I know the term heap is essientially useable memory, but what type of memory does this correlate to in the uC datasheet?

Are there alternative ways to do this? The demo code also includes an array stored in a seperate C file (ImageData.c attached), so why would you use malloc here and not do it the same way?

What are the best solutions around this?

Thanks in advance for any help! Please correct me where I have stated anything incorrect, I'm here to learn!  :D

EDIT: Additional Information below.

I am using an STM32L152RB (STM32L-Discovery) which has 16kB of RAM. Also see variables below:

```<code>// Display resolution
#define EPD_WIDTH       122
#define EPD_HEIGHT      250
</code>```

FULL demo code can be found here: https://www.waveshare.com/wiki/File:2.13inch_e-paper_code(V2).7z

All I have done is port the pins over and removed the printf/debug lines as I don't have an USB to TTL converter at the moment.

答:
do  not use malloc dynamic allocation in the embedded projects.

if you decide to malloc (assuming the standard STM generated startup) you need to change the linker script where the heap size is defined.  To check the available heap memory (still considering STM glibc implementatn) you need to amend the sbrk implementation. change the static heap position to the global variable and using provided by the linker script symbols check how many memory left.

Body:
I'm kinda new to C but feel I have a good basic understanding and hence have posted the question here.

I am trying to port over some demo code for a Waveshare E-paper display to use for an application in my Graduate Project. For now I just wanted to prove the demo code works but will most likely use aspects of it later on.

The issue I am currently having is with use of the following lines:

// Create a new image cache
UBYTE *BlackImage;
UWORD Imagesize = ((EPD_WIDTH % 8 == 0)? (EPD_WIDTH / 8 ): (EPD_WIDTH / 8 + 1)) * EPD_HEIGHT;
if((BlackImage = (UBYTE *)malloc(Imagesize)) == NULL)
    {
    printf("Failed to apply for memory...\r\n");
    return -1;
}

I am pretty sure my understanding of this is correct, but the essentially:

A pointer is created for BlackImage

The size of memory to be allocated for Blackimage is decided based of the display dimensions

In the if statement, BlackImage is assigned the memory size from the above line, and rerturns the pointer value for BlackImage. If this pointer value is NULL (i.e. 0) then the memory has not been allocated.

My code is always failing at 'applying this memory'. I assume the reasons are that I do not have enough memory available.. but here are my questions:

If I do not have enough memory - where do I look to find this out? (I am using Keil uVision IDE)

Can I solve this by shifting memory allocations round? Does malloc store in a specific type of memory? I know the term heap is essientially useable memory, but what type of memory does this correlate to in the uC datasheet?

Are there alternative ways to do this? The demo code also includes an array stored in a seperate C file (ImageData.c attached), so why would you use malloc here and not do it the same way?

What are the best solutions around this?

Thanks in advance for any help! Please correct me where I have stated anything incorrect, I'm here to learn!  :D

EDIT: Additional Information below.

I am using an STM32L152RB (STM32L-Discovery) which has 16kB of RAM. Also see variables below:

// Display resolution
#define EPD_WIDTH       122
#define EPD_HEIGHT      250

FULL demo code can be found here: https://www.waveshare.com/wiki/File:2.13inch_e-paper_code(V2).7z

All I have done is port the pins over and removed the printf/debug lines as I don't have an USB to TTL converter at the moment.


问:
Trouble performing Python unittest on class
I'm having trouble performing a simple unittest on a class I created. I'm getting this error:

AssertionError: <main.MathClass object at 0x7fc7e0340940> != 18

```<code>import unittest

class MathClass:
    def __init__(self):
        self.result = 0

    def add(self, num, *nums):
        self.result += num + sum(nums)
        return self

    def subtract(self, num, *nums):
        self.result -= (num + sum(nums))
        return self

class MathTest(unittest.TestCase):
    def testAdd(self):
        self.assertEqual(self.result.add(4,5,9), 18)

    def setUp(self):
        self.result = MathClass()

if __name__ == "__main__":
    unittest.main()
</code>```

答:
In your unit test you make a result object which is a MathClass object `:

def setUp(self):
    self.result = MathClass()
```

<p>You later invoke the <code>add</code> method of the MathClass object.
The problem is that your <code>add</code> method returns <code>self</code>, e.g. the Math object itself.</p>

<pre class="lang-py prettyprint-override"><code>def add(self, num, *nums):
    self.result += num + sum(nums)
    return self
</code>```

Internally, the MathClass.result may be changed but add still returns the Math object.

Therefore your assertEquals check compares the Math object and an int (18). Which are not equal :)

If you want to keep your variable names you may create a local variable that gets the MathClass object's result and compares it to 18:

def testAdd(self):
    self.result.add(4,5,9)
    value = self.result.result
    self.assertEqual(value, 18)
```

Or whatever other option you find more appropriate.

Body:
I'm having trouble performing a simple unittest on a class I created. I'm getting this error:

AssertionError: <main.MathClass object at 0x7fc7e0340940> != 18

import unittest

class MathClass:
    def __init__(self):
        self.result = 0

    def add(self, num, *nums):
        self.result += num + sum(nums)
        return self

    def subtract(self, num, *nums):
        self.result -= (num + sum(nums))
        return self

class MathTest(unittest.TestCase):
    def testAdd(self):
        self.assertEqual(self.result.add(4,5,9), 18)

    def setUp(self):
        self.result = MathClass()

if __name__ == "__main__":
    unittest.main()

Body:
In your unit test you make a result object which is a MathClass object `:

def setUp(self):
    self.result = MathClass()

You later invoke the add method of the MathClass object.
The problem is that your add method returns self, e.g. the Math object itself.

def add(self, num, *nums):
    self.result += num + sum(nums)
    return self

Internally, the MathClass.result may be changed but add still returns the Math object.

Therefore your assertEquals check compares the Math object and an int (18). Which are not equal :)

If you want to keep your variable names you may create a local variable that gets the MathClass object's result and compares it to 18:

def testAdd(self):
    self.result.add(4,5,9)
    value = self.result.result
    self.assertEqual(value, 18)

Or whatever other option you find more appropriate.


问:
About speedy mass deletion of users in Kentico10
I want to delete more than 1 million User information in Kentico10.

I tried to delete it with UserInfoProvider.DeleteUser (); (see the following documentation), but it is expected that it will take nearly one year with a simple calculation.
https://docs.kentico.com/api10/configuration/users#Users-Deletingauser

Because it's a simple calculation, I think it's actually a bit shorter, but it still takes time.
Is there any other way to delete users in a short time?

答: Why don't you delete them with SQL query? - I believe it will be much faster.</p>


问:
Why my program executed after I cancel BackgroundWorker?
I am practicing to use BackgroundWorker to do some time-consuming jobs.
My goal is showing all the file paths on UI.

I press the RUN button and press the CANCEL button after executing it for 5 seconds. It works fine.

Then I repeat the above steps, I notice that "Check_File" is executed for the third time.

I think that it shall be only two times.

The UI shows like below:

Searching for Files → Many FileName Appear → Canceled

Searching for Files → Many FileName Appear → Searching for Files → Canceled

The following is my code:

```<code>private void Run_Click(object sender, RoutedEventArgs e)
{
  worker.WorkerSupportsCancellation = true;
  worker.WorkerReportsProgress = true;
  worker.DoWork += Worker_DoWork;
  worker.ProgressChanged += Worker_ProgressChanged;
  worker.RunWorkerAsync(PText.Text);
  worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}

private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true)
  {
    FLabel.Content = "Canceled";
  }
  else
  {
    FLabel.Content = "Finish";
  }

  worker.Dispose();
}

private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  FLabel.Content = e.UserState.ToString();
}

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
  Check_File("My_Folder_Path", (String)e.Argument, e);
}

private void Cancel_Click(object sender, RoutedEventArgs e)
{
  worker.CancelAsync();
}

public void Check_File(string Path, string FindStr, DoWorkEventArgs e)
{
  string v_alert;

  i += 1;

  try
  {
    if (Path.LastIndexOf('\\') != Path.Length)
    {
      Path = string.Concat(Path, "\\");
    }

    if (Directory.Exists(Path))
    {
      worker.ReportProgress(0, string.Concat("Searching for Files...", i.ToString()));

      string[] Files = Directory.GetFiles(Path);

      if (Files.Length != 0)
      {
        foreach (string f in Files)
        {
          if (worker.CancellationPending == true)
          {
            e.Cancel = true;
            break;
          }

          worker.ReportProgress(Array.IndexOf(Files, f) / Files.Length * 100, f);
        }
      }
    }
    else
    {
      v_alert = string.Concat("No Path：", Path);
      MessageBox.Show(v_alert);
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}
</code>```

答:
Everytime you press the button you add an event to the worker.

```<code>private void Run_Click(object sender, RoutedEventArgs e)
{
    worker.WorkerSupportsCancellation = true;
    worker.WorkerReportsProgress = true;
    worker.DoWork += Worker_DoWork;                         //<----Happens here
    worker.ProgressChanged += Worker_ProgressChanged;
    worker.RunWorkerAsync(PText.Text);
    worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}
</code>```

So if you press it once. The worker has one event attached. If you press it a second time, the worker get attached another event. Hes now has two events. Hes runs again (this time with 2 events) and there is a total of three runs.

You should set up the worker somewhere else.

```<code>public Form1()
{
    InitializeComponent();

    //Init the worker here...
    worker.WorkerSupportsCancellation = true;
    worker.WorkerReportsProgress = true;
    worker.DoWork += Worker_DoWork;
    worker.ProgressChanged += Worker_ProgressChanged;
    worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}

private void Run_Click(object sender, RoutedEventArgs e)
{
    //only run the worker here
    worker.RunWorkerAsync(PText.Text);
}
</code>```

As Shocky mentioned in the comments, you could also remove the existing event before you attach a new one.

Body:
I am practicing to use BackgroundWorker to do some time-consuming jobs.
My goal is showing all the file paths on UI.

I press the RUN button and press the CANCEL button after executing it for 5 seconds. It works fine.

Then I repeat the above steps, I notice that "Check_File" is executed for the third time.

I think that it shall be only two times.

The UI shows like below:

Searching for Files → Many FileName Appear → Canceled

Searching for Files → Many FileName Appear → Searching for Files → Canceled

The following is my code:

private void Run_Click(object sender, RoutedEventArgs e)
{
  worker.WorkerSupportsCancellation = true;
  worker.WorkerReportsProgress = true;
  worker.DoWork += Worker_DoWork;
  worker.ProgressChanged += Worker_ProgressChanged;
  worker.RunWorkerAsync(PText.Text);
  worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}

private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled == true)
  {
    FLabel.Content = "Canceled";
  }
  else
  {
    FLabel.Content = "Finish";
  }

  worker.Dispose();
}

private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
  FLabel.Content = e.UserState.ToString();
}

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
  Check_File("My_Folder_Path", (String)e.Argument, e);
}

private void Cancel_Click(object sender, RoutedEventArgs e)
{
  worker.CancelAsync();
}

public void Check_File(string Path, string FindStr, DoWorkEventArgs e)
{
  string v_alert;

  i += 1;

  try
  {
    if (Path.LastIndexOf('\\') != Path.Length)
    {
      Path = string.Concat(Path, "\\");
    }

    if (Directory.Exists(Path))
    {
      worker.ReportProgress(0, string.Concat("Searching for Files...", i.ToString()));

      string[] Files = Directory.GetFiles(Path);

      if (Files.Length != 0)
      {
        foreach (string f in Files)
        {
          if (worker.CancellationPending == true)
          {
            e.Cancel = true;
            break;
          }

          worker.ReportProgress(Array.IndexOf(Files, f) / Files.Length * 100, f);
        }
      }
    }
    else
    {
      v_alert = string.Concat("No Path：", Path);
      MessageBox.Show(v_alert);
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

Body:
Everytime you press the button you add an event to the worker.

private void Run_Click(object sender, RoutedEventArgs e)
{
    worker.WorkerSupportsCancellation = true;
    worker.WorkerReportsProgress = true;
    worker.DoWork += Worker_DoWork;                         //<----Happens here
    worker.ProgressChanged += Worker_ProgressChanged;
    worker.RunWorkerAsync(PText.Text);
    worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}

So if you press it once. The worker has one event attached. If you press it a second time, the worker get attached another event. Hes now has two events. Hes runs again (this time with 2 events) and there is a total of three runs.

You should set up the worker somewhere else.

public Form1()
{
    InitializeComponent();

    //Init the worker here...
    worker.WorkerSupportsCancellation = true;
    worker.WorkerReportsProgress = true;
    worker.DoWork += Worker_DoWork;
    worker.ProgressChanged += Worker_ProgressChanged;
    worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
}

private void Run_Click(object sender, RoutedEventArgs e)
{
    //only run the worker here
    worker.RunWorkerAsync(PText.Text);
}

As Shocky mentioned in the comments, you could also remove the existing event before you attach a new one.