问:
How to implement snake_case for Swagger documentation in spring-boot-starter-data-rest?
I am using swagger for the documentation of spring-boot-starter-data-rest project. In application.properties file, I have configured: spring.jackson.property-naming-strategy=SNAKE_CASE naming strategy but unfortunately, I am getting camelCase in swagger documentation. But, the same configuration is working if I change the project from spring-boot-starter-data-rest to spring-boot-starter-web. Below are the dependencies I am using with spring boot 2.1.1.RELEASE.

```<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>
            <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.1.1.RELEASE</version>
                <relativePath/> <!-- lookup parent from repository -->
            </parent>
            <groupId>com.example</groupId>
            <artifactId>demo1</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <name>demo1</name>
            <description>Demo project for Spring Boot</description>
            <properties>
                <java.version>1.8</java.version>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>io.springfox</groupId>
                    <artifactId>springfox-swagger-ui</artifactId>
                    <version>2.9.2</version>
                </dependency>
                <dependency>
                    <groupId>io.springfox</groupId>
                    <artifactId>springfox-swagger2</artifactId>
                    <version>2.9.2</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-rest</artifactId>
                </dependency>
            </dependencies>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </project>
</code>```

application.properties

```<code>        spring.jackson.property-naming-strategy=SNAKE_CASE
</code>```

package com.example.demo1;

```<code>    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    public class Demo1Application {

        public static void main(String[] args) {
            SpringApplication.run(Demo1Application.class, args);

        }

    }
</code>```

SwaggerConfig

```<code>    package com.example.demo1;

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.PropertyNamingStrategy;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    import
    org.springframework.data.web.config.SpringDataJacksonConfiguration;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;

    import java.util.ArrayList;

    @Configuration
    @EnableSwagger2
    @Import({SpringDataJacksonConfiguration.class})
    public class SwaggerConfig {

        public static ApiInfo metaData(String info) {
            return new ApiInfo(info,
                    "Th",
                    "1.0", "httn.html",
                    new Contact("Thd", "", "thoom"), "decense",
                    "https", new ArrayList());
        }

        @Bean
        public Docket cashFlowApi() {
            return new Docket(DocumentationType.SWAGGER_2).groupName("-caching").select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo1"))
                    .paths(PathSelectors.any())
                    .build()
                    .apiInfo(SwaggerConfig.metaData("BOcPI"));
        }
    }
</code>```

StoreController

```<code>    package com.example.demo1;

    import java.util.Arrays;
    import java.util.List;

    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import io.swagger.annotations.ApiResponse;
    import io.swagger.annotations.ApiResponses;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    @CrossOrigin
    public class StoreController {

        @GetMapping(value = "/v1/storeMap")
        @ApiOperation(value = "Returns the list of stores", notes = "Returns the list of stores with pagination.")
        @ApiResponses(value = {@ApiResponse(code = 200, message = "Successfully retrieved the stores list"),
                @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 206, message = "Partial Content"),
                @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
                @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
                @ApiResponse(code = 404, message = "The resource you were trying to reach is not found"),
                @ApiResponse(code = 500, message = "A technical error happened")})

        public ResponseEntity<Store> getStore(
                @RequestParam(name = "country_code", required = false) @ApiParam(value = "the code)") String countryCode
                ) {

            return ResponseEntity.ok(new Store(1,"ZZ"));
        }

    }
</code>```

Now with this configuration, in API POST method is expecting snake_case and in the documentation, swagger is showing camelCase. I don't have the option either to change from snake_case to camelCase or spring-boot-starter-data-rest to spring-boot-starter-web.

答:
I also have a Spring Boot + Swagger project with the same issue, but using Spring the io.swagger packages without the Springfox libraries and using the Gradle plugin com.benjaminsproule.swagger to generate the docs. So to solve the issue I added this line ModelConverters.getInstance().addConverter(new ModelResolver(objectMapper)) (it's a hack, I'm not using an official API, but it worked):

package com.company.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.converter.ModelConverters;
import io.swagger.jackson.ModelResolver;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.*;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class SwaggerConfig extends ResourceConfig {

  @Autowired ObjectMapper objectMapper;

  @PostConstruct public void configureSwagger() {
    // Available at localhost:port/swagger.json
    this.register(ApiListingResource.class);
    this.register(SwaggerSerializers.class);

    BeanConfig config = new BeanConfig();
    config.setConfigId("api-springboot-jersey-swagger");
    config.setTitle("Company API");
    config.setResourcePackage("com.company.api");
    config.setPrettyPrint(true);
    config.setScan(true);
    // With this hack we inject into Swagger the same object mapper
    // used by Spring (spring.jackson.property-naming-strategy)
    ModelConverters.getInstance().addConverter(new ModelResolver(objectMapper));
  }
}
```

Body:
I am using swagger for the documentation of spring-boot-starter-data-rest project. In application.properties file, I have configured: spring.jackson.property-naming-strategy=SNAKE_CASE naming strategy but unfortunately, I am getting camelCase in swagger documentation. But, the same configuration is working if I change the project from spring-boot-starter-data-rest to spring-boot-starter-web. Below are the dependencies I am using with spring boot 2.1.1.RELEASE.

<?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>
            <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.1.1.RELEASE</version>
                <relativePath/>
            </parent>
            <groupId>com.example</groupId>
            <artifactId>demo1</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <name>demo1</name>
            <description>Demo project for Spring Boot</description>
            <properties>
                <java.version>1.8</java.version>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>io.springfox</groupId>
                    <artifactId>springfox-swagger-ui</artifactId>
                    <version>2.9.2</version>
                </dependency>
                <dependency>
                    <groupId>io.springfox</groupId>
                    <artifactId>springfox-swagger2</artifactId>
                    <version>2.9.2</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-rest</artifactId>
                </dependency>
            </dependencies>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </project>

application.properties

        spring.jackson.property-naming-strategy=SNAKE_CASE

package com.example.demo1;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    public class Demo1Application {

        public static void main(String[] args) {
            SpringApplication.run(Demo1Application.class, args);

        }

    }

SwaggerConfig

    package com.example.demo1;

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.PropertyNamingStrategy;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    import
    org.springframework.data.web.config.SpringDataJacksonConfiguration;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;

    import java.util.ArrayList;

    @Configuration
    @EnableSwagger2
    @Import({SpringDataJacksonConfiguration.class})
    public class SwaggerConfig {

        public static ApiInfo metaData(String info) {
            return new ApiInfo(info,
                    "Th",
                    "1.0", "httn.html",
                    new Contact("Thd", "", "thoom"), "decense",
                    "https", new ArrayList());
        }

        @Bean
        public Docket cashFlowApi() {
            return new Docket(DocumentationType.SWAGGER_2).groupName("-caching").select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo1"))
                    .paths(PathSelectors.any())
                    .build()
                    .apiInfo(SwaggerConfig.metaData("BOcPI"));
        }
    }

StoreController

    package com.example.demo1;

    import java.util.Arrays;
    import java.util.List;

    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import io.swagger.annotations.ApiResponse;
    import io.swagger.annotations.ApiResponses;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    @CrossOrigin
    public class StoreController {

        @GetMapping(value = "/v1/storeMap")
        @ApiOperation(value = "Returns the list of stores", notes = "Returns the list of stores with pagination.")
        @ApiResponses(value = {@ApiResponse(code = 200, message = "Successfully retrieved the stores list"),
                @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 206, message = "Partial Content"),
                @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
                @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
                @ApiResponse(code = 404, message = "The resource you were trying to reach is not found"),
                @ApiResponse(code = 500, message = "A technical error happened")})

        public ResponseEntity<Store> getStore(
                @RequestParam(name = "country_code", required = false) @ApiParam(value = "the code)") String countryCode
                ) {

            return ResponseEntity.ok(new Store(1,"ZZ"));
        }

    }

Now with this configuration, in API POST method is expecting snake_case and in the documentation, swagger is showing camelCase. I don't have the option either to change from snake_case to camelCase or spring-boot-starter-data-rest to spring-boot-starter-web.


来源: stackexchange

问:
Entity Framework - Filtering rows with where() after include
If I have two objects or models as below:

```<code>   class School
    {
        ICollection<Student> students { get; set; }
    }

    class Student
    {
        string Name { get; set; }
        School school { get; set; }
        bool Deleted { get; set; }
    }
</code>```

Howcome when trying to get a school with only students that are not deleted doesn't work properly using the where clause?

```<code>var school = DatabaseContext.Schools
             .Include(x => x.Students)
             .Where(y => !y.Deleted).FirstOrDefault();
</code>```

Shouldn't the where clause filter the students that are not deleted? Using where clause inside the include is not allowed too without using any third party libs.

答:
This is what you should do to get desired result</p>

```<code>var result = mydbcontext.Schools
                        .Include(d => d.students)
                        .Where(d => d.Id == 1) //the where clause filters only Schools
                        .Select(x=>new School
                        {
                            Id=x.Id,
                            students =x.students.Where(s=>!s.Deleted).ToList()
                        })
                        .AsNoTracking()
                        .ToList();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I have two objects or models as below:

   class School
    {
        ICollection<Student> students { get; set; }
    }

    class Student
    {
        string Name { get; set; }
        School school { get; set; }
        bool Deleted { get; set; }
    }

Howcome when trying to get a school with only students that are not deleted doesn't work properly using the where clause?

var school = DatabaseContext.Schools
             .Include(x => x.Students)
             .Where(y => !y.Deleted).FirstOrDefault();

Shouldn't the where clause filter the students that are not deleted? Using where clause inside the include is not allowed too without using any third party libs.

Body:
This is what you should do to get desired result

var result = mydbcontext.Schools
                        .Include(d => d.students)
                        .Where(d => d.Id == 1) //the where clause filters only Schools
                        .Select(x=>new School
                        {
                            Id=x.Id,
                            students =x.students.Where(s=>!s.Deleted).ToList()
                        })
                        .AsNoTracking()
                        .ToList();


问:
How can I use a word boundary regex in the findstr utility
I am searching a folder looking for files which contain the word car. This is a sample of the data I'm working with, obtained by using the findstr utility - findstr /s /i /n car *.*

interview-290346:1:Drives a similar car to the description.

interview-29316965:3:time.) 'You're nothing but a pack of cards!'

interview-676473:7:The next witness was the Duchess's cook. She carried the pepper-box in

interview-3804339:1:Park's car is red, not blue, and the person on the camera is presumed to be male.  Not considered a suspect.

I want to find the files which contain the word car, but not words which contain the substring car. I have tried to use the findstr utility with the regex car\b but I can't work out how to escape it properly. None of the below return any results:

```<code>findstr /s /i /n car\b *.*
findstr /s /i /n "car\b" *.*
findstr /s /i /n car\\b *.*
findstr /s /i /n car\\\\b *.*
findstr /s /i /n "car\\b" *.*
findstr /s /i /n "car\\\\b" *.*
</code>```

What is the correct way to escape the regex, and is there something else I need to do in order to use it within findstr? (I did notice after typing this that the regex will still match words with the car substring at the end of the word, but that's ok. My question isn't about what regex to use, but how to escape it for use in findstr.)

(If anyone is interested in the context of this question, I'm working through the Command Line murder mystery.)

答: Judging by the documentation, findstr doesn't understand \b. You could  use an inverse class instead, e.g. "car[^a-z]" (untested), although that wouldn't match if "car" was the last thing in the file. (You could maybe invoke findstr with a different expression to catch those.)

Body:
I am searching a folder looking for files which contain the word car. This is a sample of the data I'm working with, obtained by using the findstr utility - findstr /s /i /n car *.*

interview-290346:1:Drives a similar car to the description.

interview-29316965:3:time.) 'You're nothing but a pack of cards!'

interview-676473:7:The next witness was the Duchess's cook. She carried the pepper-box in

interview-3804339:1:Park's car is red, not blue, and the person on the camera is presumed to be male.  Not considered a suspect.

I want to find the files which contain the word car, but not words which contain the substring car. I have tried to use the findstr utility with the regex car\b but I can't work out how to escape it properly. None of the below return any results:

findstr /s /i /n car\b *.*
findstr /s /i /n "car\b" *.*
findstr /s /i /n car\\b *.*
findstr /s /i /n car\\\\b *.*
findstr /s /i /n "car\\b" *.*
findstr /s /i /n "car\\\\b" *.*

What is the correct way to escape the regex, and is there something else I need to do in order to use it within findstr? (I did notice after typing this that the regex will still match words with the car substring at the end of the word, but that's ok. My question isn't about what regex to use, but how to escape it for use in findstr.)

(If anyone is interested in the context of this question, I'm working through the Command Line murder mystery.)


问:
Django admin list_display weirdly slow with foreign keys
Django 1.2.5
Python: 2.5.5

My admin list of a sports model has just gone really slow (5 minutes for 400 records). It was returning in a second or so until we got 400 games, 50 odd teams and 2 sports.

I have fixed it in an awful way so I'd like to see if anyone has seen this before. My app looks like this:

```<code>models:

Sport( models.Model )
    name

Venue( models.Model )
    name

Team( models.Model )
    name

Fixture( models.Model )
    date
    sport = models.ForeignKey(Sport)
    venue = models.ForeignKey(Venue)

TeamFixture( Fixture )
    team1 = models.ForeignKey(Team, related_name="Team 1")
    team2 = models.ForeignKey(Team, related_name="Team 2")

admin:

TeamFixture_ModelAdmin (ModelAdmin)
    list_display = ('date','sport','venue','team1','team2',)
</code>```

If I remove any foreign keys from list_display then it's quick. As soon as I add any foreign key then slow.

I fixed it by using non foreign keys but calculating them in the model init so this works:

```<code>models:

TeamFixture( Fixture )
    team1 = models.ForeignKey(Team, related_name="Team 1")
    team2 = models.ForeignKey(Team, related_name="Team 2")
    sport_name = ""
    venue_name = ""
    team1_name = ""
    team2_name = ""

    def __init__(self, *args, **kwargs):
        super(TeamFixture, self).__init__(*args, **kwargs)

        self.sport_name = self.sport.name
        self.venue_name = self.venue.name
        self.team1_name = self.team1.name
        self.team2_name = self.team2.name

admin:

TeamFixture_ModelAdmin (ModelAdmin)
    list_display = ('date','sport_name','venue_name','team1_name','team2_name',)
</code>```

Administration for all other models are fine with several thousand records at the moment and all views in the actual site is functioning fine.

答: I fixed my problem by setting list_select_related to the list of related model fields instead of just True

ContentLicense: CC BY-SA 2.5

Body:
Django 1.2.5
Python: 2.5.5

My admin list of a sports model has just gone really slow (5 minutes for 400 records). It was returning in a second or so until we got 400 games, 50 odd teams and 2 sports.

I have fixed it in an awful way so I'd like to see if anyone has seen this before. My app looks like this:

models:

Sport( models.Model )
    name

Venue( models.Model )
    name

Team( models.Model )
    name

Fixture( models.Model )
    date
    sport = models.ForeignKey(Sport)
    venue = models.ForeignKey(Venue)

TeamFixture( Fixture )
    team1 = models.ForeignKey(Team, related_name="Team 1")
    team2 = models.ForeignKey(Team, related_name="Team 2")

admin:

TeamFixture_ModelAdmin (ModelAdmin)
    list_display = ('date','sport','venue','team1','team2',)

If I remove any foreign keys from list_display then it's quick. As soon as I add any foreign key then slow.

I fixed it by using non foreign keys but calculating them in the model init so this works:

models:

TeamFixture( Fixture )
    team1 = models.ForeignKey(Team, related_name="Team 1")
    team2 = models.ForeignKey(Team, related_name="Team 2")
    sport_name = ""
    venue_name = ""
    team1_name = ""
    team2_name = ""

    def __init__(self, *args, **kwargs):
        super(TeamFixture, self).__init__(*args, **kwargs)

        self.sport_name = self.sport.name
        self.venue_name = self.venue.name
        self.team1_name = self.team1.name
        self.team2_name = self.team2.name

admin:

TeamFixture_ModelAdmin (ModelAdmin)
    list_display = ('date','sport_name','venue_name','team1_name','team2_name',)

Administration for all other models are fine with several thousand records at the moment and all views in the actual site is functioning fine.


问:
pandas groupby apply the same function to multiple columns
I have a dataframe that looks like:

```<code>>>> df = pd.DataFrame({'id':[1,1,1,1,1,2,2,2],'month':[1,1,2,2,2,1,2,2],'value1':[1,1,3,3,5,6,7,7], 'value2': [9,10,11,12,12,14,15,15], 'others': range(8)})
>>> df

   id  month  value1  value2  others
0   1      1       1       9       0
1   1      1       1      10       1
2   1      2       3      11       2
3   1      2       3      12       3
4   1      2       5      12       4
5   2      1       6      14       5
6   2      2       7      15       6
7   2      2       7      15       7
</code>```

I want to do perform a custom function whose input is a series on value1 and value2:

```<code>def get_most_common(srs):
    """
    Returns the most common value in a list. For ties, it returns whatever
    value collections.Counter.most_common(1) gives.
    """
    from collections import Counter

    x = list(srs)
    my_counter = Counter(x)
    most_common_value = my_counter.most_common(1)[0][0]

    return most_common_value
</code>```

Expected result:

```<code>               value1    value2
   id  month
   1      1       1       9
          2       3      12
   2      1       6      14
          2       7      15
</code>```

The function was written like that because initially I only had to apply it to a single column (value1) so df = df.groupby(['id,'month'])['value1'].apply(get_most_common) worked. Now I have to apply it to two columns simultaneously.

Attempts:

Apply

df = df.groupby(['id,'month'])[['value1','value2']].apply(get_most_common) gave:

```<code>id  month
1   1        value1
    2        value1
2   1        value1
    2        value1
</code>```

Transform

df = df.groupby(['id,'month'])[['value1','value2']].transform(get_most_common)

gave this

```<code>   value1  value2
0       1       9
1       1       9
2       3      12
3       3      12
4       3      12
5       6      14
6       7      15
7       7      15
</code>```

applymap doesn't work.

What am I missing here?

答:
Use GroupBy.agg - it run function for each column separately:

```<code>df = df.groupby(['id','month'])['value1','value2'].agg(get_most_common)
print (df)
          value1  value2
id month
1  1           1       9
   2           3      12
2  1           6      14
   2           7      15
</code>```

Body:
I have a dataframe that looks like:

>>> df = pd.DataFrame({'id':[1,1,1,1,1,2,2,2],'month':[1,1,2,2,2,1,2,2],'value1':[1,1,3,3,5,6,7,7], 'value2': [9,10,11,12,12,14,15,15], 'others': range(8)})
>>> df

   id  month  value1  value2  others
0   1      1       1       9       0
1   1      1       1      10       1
2   1      2       3      11       2
3   1      2       3      12       3
4   1      2       5      12       4
5   2      1       6      14       5
6   2      2       7      15       6
7   2      2       7      15       7

I want to do perform a custom function whose input is a series on value1 and value2:

def get_most_common(srs):
    """
    Returns the most common value in a list. For ties, it returns whatever
    value collections.Counter.most_common(1) gives.
    """
    from collections import Counter

    x = list(srs)
    my_counter = Counter(x)
    most_common_value = my_counter.most_common(1)[0][0]

    return most_common_value

Expected result:

               value1    value2
   id  month
   1      1       1       9
          2       3      12
   2      1       6      14
          2       7      15

The function was written like that because initially I only had to apply it to a single column (value1) so df = df.groupby(['id,'month'])['value1'].apply(get_most_common) worked. Now I have to apply it to two columns simultaneously.

Attempts:

Apply

df = df.groupby(['id,'month'])[['value1','value2']].apply(get_most_common) gave:

id  month
1   1        value1
    2        value1
2   1        value1
    2        value1

Transform

df = df.groupby(['id,'month'])[['value1','value2']].transform(get_most_common)

gave this

   value1  value2
0       1       9
1       1       9
2       3      12
3       3      12
4       3      12
5       6      14
6       7      15
7       7      15

applymap doesn't work.

What am I missing here?

Body:
Use GroupBy.agg - it run function for each column separately:

df = df.groupby(['id','month'])['value1','value2'].agg(get_most_common)
print (df)
          value1  value2
id month
1  1           1       9
   2           3      12
2  1           6      14
   2           7      15


问:
How to exclude a color from git's graphColors?
I'd like to customize the colors used in git log --graph via log.graphColors. Basically, I need to keep the default colors, just exclude the blue color as it's barely readable in my terminal. What would be the cleanest way to do that?

答:
This is the original colorset:

```<code>red,green,yellow,blue,magenta,cyan,bold red,bold green,bold yellow,bold blue,bold magenta,bold cyan
</code>```

You can skip the blue and set this in your .gitconfig file:

```<code>[log]
    graphColors = red,green,yellow,magenta,cyan,bold red,bold green,bold yellow,bold magenta,bold cyan
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is the original colorset:

red,green,yellow,blue,magenta,cyan,bold red,bold green,bold yellow,bold blue,bold magenta,bold cyan

You can skip the blue and set this in your .gitconfig file:

[log]
    graphColors = red,green,yellow,magenta,cyan,bold red,bold green,bold yellow,bold magenta,bold cyan


问:
Vector of class object with private constructor and destructor?
Defining the classes A with private constructor and destructor (it should be so!) and B as a friend class, how can I creat a vector of A objects in B and fill it with the function addA(). I got the error "error C2248: "A::~A": No access to private members whose declaration was made in the A class".</p>

```<code>class A
{
private:
    A();
    A(const std::string& name, const float& num);
    ~A();
public:
    friend class B;
private:
    std::string name_;
    float num_;
};

A::A()
{
    name_ = "NoName";
    num_ = 0.0;
}
A::A(const std::string& name, const float& num)
{
    name_ = name;
    num_ = num;
}
A::~A()
{
}

class B
{
public:
    B();
    ~B();
    void addA(const std::string name, const float num);
private:
    vector<A> vecA;
};

B::B()
{
}
B::~B()
{
}
void B::addA(const std::string name, const float num)
{
    A a(name, num);
    vecA.push_back(a);
}

int main()
{
    B b;
    b.addA("Name", 1.0);

    return 0;
}
</code>```

答:
While @Fureeish has a neat solution, here's a slightly simpler alternative: just wrap it.

```<code>class AccessPrivate;

class PrivStuff
{
private:
    PrivStuff() {}
    ~PrivStuff() {}
public:
    friend class AccessPrivate;

    std::string m_data{};
};

class AccessPrivate
{
public:
    AccessPrivate() = default;
    ~AccessPrivate() = default;

    PrivStuff m_priv;
};

int main(int argc, char* argv[])
{
    std::vector<AccessPrivate> myvec;
    myvec.resize(4);

    for (auto& stuff : myvec)
    {
        stuff.m_priv.m_data = "heya";
    }

}
</code>```

If you need something more complicated, like passing in arguments, just add an equivalent constructor to AccessPrivate and there you go.  You can essentially treat AccessPrivate almost like the actual private class, just one level of indirection.

Body:
Defining the classes A with private constructor and destructor (it should be so!) and B as a friend class, how can I creat a vector of A objects in B and fill it with the function addA(). I got the error "error C2248: "A::~A": No access to private members whose declaration was made in the A class".

class A
{
private:
    A();
    A(const std::string& name, const float& num);
    ~A();
public:
    friend class B;
private:
    std::string name_;
    float num_;
};

A::A()
{
    name_ = "NoName";
    num_ = 0.0;
}
A::A(const std::string& name, const float& num)
{
    name_ = name;
    num_ = num;
}
A::~A()
{
}

class B
{
public:
    B();
    ~B();
    void addA(const std::string name, const float num);
private:
    vector vecA;
};

B::B()
{
}
B::~B()
{
}
void B::addA(const std::string name, const float num)
{
    A a(name, num);
    vecA.push_back(a);
}

int main()
{
    B b;
    b.addA("Name", 1.0);

    return 0;
}

Body:
While @Fureeish has a neat solution, here's a slightly simpler alternative: just wrap it.

class AccessPrivate;

class PrivStuff
{
private:
    PrivStuff() {}
    ~PrivStuff() {}
public:
    friend class AccessPrivate;

    std::string m_data{};
};

class AccessPrivate
{
public:
    AccessPrivate() = default;
    ~AccessPrivate() = default;

    PrivStuff m_priv;
};

int main(int argc, char* argv[])
{
    std::vector<AccessPrivate> myvec;
    myvec.resize(4);

    for (auto& stuff : myvec)
    {
        stuff.m_priv.m_data = "heya";
    }

}

If you need something more complicated, like passing in arguments, just add an equivalent constructor to AccessPrivate and there you go.  You can essentially treat AccessPrivate almost like the actual private class, just one level of indirection.


问:
Using composite within a loop in ImageMagick
I am trying to use the Command Prompt in Windows 10 to run a loop on a batch of files in ImageMagick. As an example for a single image, the command I would use in IM is

```<code> magick composite -geometry +5+10 imageA.png background.png
</code>```

This works fine when I work with images individually.

However, I have a batch of 700+ images (let's call them imageA.png, imageB.png, imageC.png, imageD.png) and I want to overlay each of them onto background.png. I have tried using the following code:

```<code> FOR %i IN (1) DO magick composite -geometry +5+10 *.png background.png %i_composite.png
</code>```

This generates an output of one image, with each image overlayed on top of eachother. What I want to do is, for each *.png image in the directory %i, overlay it onto background.png and save it with the extension filenumber_composite.png.

For info, the loop works when I try to use a different kind of transformation (reducing the size of the image by a given %), but fails when I use the composite command.

答:
Your "for" command is wrong. Try this with the "*.png" in the parentheses...

```<code>FOR %i IN (*.png) DO magick composite -geometry +5+10 %i background.png %i_composite.png
</code>```

That means for each file in the group of *.png do the following action with "%i", which represents each one of those .png files in sequence.

Body:
I am trying to use the Command Prompt in Windows 10 to run a loop on a batch of files in ImageMagick. As an example for a single image, the command I would use in IM is

 magick composite -geometry +5+10 imageA.png background.png

This works fine when I work with images individually.

However, I have a batch of 700+ images (let's call them imageA.png, imageB.png, imageC.png, imageD.png) and I want to overlay each of them onto background.png. I have tried using the following code:

 FOR %i IN (1) DO magick composite -geometry +5+10 *.png background.png %i_composite.png

This generates an output of one image, with each image overlayed on top of eachother. What I want to do is, for each *.png image in the directory %i, overlay it onto background.png and save it with the extension filenumber_composite.png.

For info, the loop works when I try to use a different kind of transformation (reducing the size of the image by a given %), but fails when I use the composite command.

Body:
Your "for" command is wrong. Try this with the "*.png" in the parentheses...

FOR %i IN (*.png) DO magick composite -geometry +5+10 %i background.png %i_composite.png

That means for each file in the group of *.png do the following action with "%i", which represents each one of those .png files in sequence.


问:
Poisson Regression with overload of zeroes SAS
I am testing different models for the best fit and most robust statistics to my data. My dataset contains over 50000 observations, approx. over 99.3% of the data are zeroes - such 0.7% are actual events.

Eventually see: https://imgur.com/a/CUuTlSK

I search to find the best fit of the following models; Logistic, Poisson, NB, ZIP, ZINB, PLH, NBLH. (NB: Negative-binomial, ZI: Zero-Inflated, P: Poisson, LH: Logit Hurdle)

The first way I tried doing this was by estimating the binary response with logistic regression.

My questions: Can I use Poisson on the binary variable or should I instead impose the binary with some integer values? For instance with the associated loss; if y=1 then y_val=y*loss. In my case, the variance of y_val becomes approx. 2.5E9. I held to use the binary variable because it does not matter, in this purpose, what the company defaulted with, default is default no matter the amount.

Both with logistic regression and Poisson, I got some terrible statistic: Very high deviance value (and 0 p-value), terrible estimates (=many of the estimated parameters are 0 -> odds ratio =1), very low confidence intervals, everything seems to be 'wrong'. If I transform the response variable to log(y_val) for y>1 in Poisson the statistics seem to get better - however, this is against the assumptions of integer count response in Poisson.

I briefly have tested the ZINB, it does not change the statistics significantly (=it does not help at all in this case).

Does there exist any proper way of dealing with such a dataset? I am interested in achieving the best fit for my data (about startup business' and their default status).

The data are cleaned and ready to be fitted. Is there anything I should be aware of that I don't have mentioned?

I use the genmod procedure in SAS with dist=Poisson, zinb, zip etc.

Thanks in advance.

答:
Sorry, my rep is too low to comment, so it has to be an answer.

You should consider undersampling technique before using any regression/model, because your target is below 5%, which makes it extremely difficult to to predict.

Undersampling is a method of cutting out non-target events, in order to increase target ratio, I really recommend considering it, I got to use it once in my practice, and it seemed pretty helpful


问:
jsx console log inside map inside return statement
I'm working inside a stateless function controller in React. I'm trying to do a console.log inside a map that is inside a return statement.
This works:

```<code>{options.map(o => (
   {console.log(o)}
))}
</code>```

And this works:

```<code>return (
   <>
      //more html/jsx code
      {console.log("test")}
      //more html/jsx code
   </>
)
</code>```

But how to log inside a map that is inside a return statement? like so:

```<code>return (
   //more html/jsx code
   {options.map(o => (
      <>
         {console.log(o)} //doesn't compile
         console.log(o) //doesn't work -> written in DOM
      </>
   ))}
   //more html/jsx code
)

</code>```

Anyone have an idea if this is possibly at all. I find many answers articles/questions where they do 1 of the 2. Or in a map or in a return statement. Can't seem to find an answer that is both in a return statement and a map. I, ofcourse, only use console.log for testing purposes

答:
You are making an implicit return in this map here and returning multiple nodes at the same level. They should always be contained into one single node, so this:

```<code>return (
   {options.map(o => (
      {console.log(o)} //doesn't compile
      {console.log(o)} //doesn't work -> writes in DOM
   ))}
)
</code>```

Should be changed to this: (notice the use of React.Fragment or <>)

```<code>return (
   {options.map(o => (
      <>
        {console.log(o)}
        {console.log(o)}
      </>
   ))}
)
</code>```

Which makes a single node out of the output and lets react render properly.

Anyway, I don't recommend retuning console.log anytime in React, you could instead do the console logs and return a null so React knows that there's nothing to render in there.

```<code>return (
   {options.map(o => {
      console.log(o)
      return null;
   })}
)
</code>```

Body:
I'm working inside a stateless function controller in React. I'm trying to do a console.log inside a map that is inside a return statement.
This works:

{options.map(o => (
   {console.log(o)}
))}

And this works:

return (
   <>
      //more html/jsx code
      {console.log("test")}
      //more html/jsx code
   </>
)

But how to log inside a map that is inside a return statement? like so:

return (
   //more html/jsx code
   {options.map(o => (
      <>
         {console.log(o)} //doesn't compile
         console.log(o) //doesn't work -> written in DOM
      </>
   ))}
   //more html/jsx code
)

Anyone have an idea if this is possibly at all. I find many answers articles/questions where they do 1 of the 2. Or in a map or in a return statement. Can't seem to find an answer that is both in a return statement and a map. I, ofcourse, only use console.log for testing purposes

Body:
You are making an implicit return in this map here and returning multiple nodes at the same level. They should always be contained into one single node, so this:

return (
   {options.map(o => (
      {console.log(o)} //doesn't compile
      {console.log(o)} //doesn't work -> writes in DOM
   ))}
)

Should be changed to this: (notice the use of React.Fragment or <>)

return (
   {options.map(o => (
      <>
        {console.log(o)}
        {console.log(o)}
      </>
   ))}
)

Which makes a single node out of the output and lets react render properly.

Anyway, I don't recommend retuning console.log anytime in React, you could instead do the console logs and return a null so React knows that there's nothing to render in there.

return (
   {options.map(o => {
      console.log(o)
      return null;
   })}
)


问:
Optional additional data on ManyToManyField
I have a ManyToManyField in Django, and I want to save additional information for the relation. What I am doing is

```<code>class Speaker(models.Model):
    name = models.CharField(max_length=50)
    title = models.CharField(max_length=100, blank=True)
    description = models.TextField(blank=True)

class Event(models.Model):
    title = models.CharField(max_length=120)
    speakers = models.ManyToManyField(Speaker, blank=True, null=True, through='Role')

class Role(models.Model):
    speaker = models.ForeignKey(Speaker)
    event = models.ForeignKey(Event)
    role = models.CharField(max_length=50, blank=True)
</code>```

As per documentation, this prevents Django from doing some automatic stuff. What is particularly annoying is that it makes the Speaker list not available when creating an Event in the admin.

I realize that in general Django does not know what to put in the Role.role field. But that is optional (blank=True). I would expect that

either Django recognizes that Role has only optional fields and lets me use the many to many relation as usual (creating the fields with an empty default), or

Django admin lets me add Speakers to a newly created event, and for each such Speaker it asks for the additional information (the value of Role.role).

The second possibility would be more useful and more general than the first. Still Django admin does none of the two: instead the speakers field is removed from the Event.

Is there a way to make Django admin behave as described above?

答: The solution lies in this answer. Briefly, one should use InlineModelAdmin, as documented here. This realizes exactly the second behaviour I described.

Body:
I have a ManyToManyField in Django, and I want to save additional information for the relation. What I am doing is

class Speaker(models.Model):
    name = models.CharField(max_length=50)
    title = models.CharField(max_length=100, blank=True)
    description = models.TextField(blank=True)

class Event(models.Model):
    title = models.CharField(max_length=120)
    speakers = models.ManyToManyField(Speaker, blank=True, null=True, through='Role')

class Role(models.Model):
    speaker = models.ForeignKey(Speaker)
    event = models.ForeignKey(Event)
    role = models.CharField(max_length=50, blank=True)

As per documentation, this prevents Django from doing some automatic stuff. What is particularly annoying is that it makes the Speaker list not available when creating an Event in the admin.

I realize that in general Django does not know what to put in the Role.role field. But that is optional (blank=True). I would expect that

either Django recognizes that Role has only optional fields and lets me use the many to many relation as usual (creating the fields with an empty default), or

Django admin lets me add Speakers to a newly created event, and for each such Speaker it asks for the additional information (the value of Role.role).

The second possibility would be more useful and more general than the first. Still Django admin does none of the two: instead the speakers field is removed from the Event.

Is there a way to make Django admin behave as described above?


问:
Powershell Query users
I have an issue with some query parts dues to some failures in the system so basically, I have to search all AD users, and check which user is member of a specific group.
Using the Get-ADgroupMember does not return anything as I can not query in the specific group, I have to work around it such as checking users and checking if they are members of the group and if so, listing them into a csv/txt file.

Any ideas on how to tackle this one?

答:
$users= Get-ADUser -Filter {name -like "" } -Properties memberof $Groups= Get-ADGroup -Filter {name -like "" } -Properties memberof
   Select-Object -ExpandProperty memberof | where memberof -EQ "Users" Foreach( $user in $users)  {

$grups= $user | Select-Object -ExpandProperty memberof

If( $grups -contains "Users,OU=txx,OU=Admin,DC=COM,DC=Digital")
      {
      Add-ADGroupMember "Users" -Members $user.Samaccountname
      } } Foreach( $grup in $groups ) {

```<code>$member = $grup | Select-Object -ExpandProperty memberof

If( $member -contains "Users,OU=txx,OU=Admin,DC=COM,DC=Digital") {

    Add-ADGroupMember "Users" -Members $grup.Name

}
    }
</code>```

Found the solution.

Title: Powershell Query users

Body:
$users= Get-ADUser -Filter {name -like "" } -Properties memberof $Groups= Get-ADGroup -Filter {name -like "" } -Properties memberof
   Select-Object -ExpandProperty memberof | where memberof -EQ "Users" Foreach( $user in $users)  {

$grups= $user | Select-Object -ExpandProperty memberof

If( $grups -contains "Users,OU=txx,OU=Admin,DC=COM,DC=Digital")
      {
      Add-ADGroupMember "Users" -Members $user.Samaccountname
      } } Foreach( $grup in $groups ) {

$member = $grup | Select-Object -ExpandProperty memberof

If( $member -contains "Users,OU=txx,OU=Admin,DC=COM,DC=Digital") {

    Add-ADGroupMember "Users" -Members $grup.Name

}
    }

Found the solution.


问:
FoxPro fxp files
I know very little about FoxPro but have a project that requires working with a third-party application, based on FoxPro, and a .fxp file.  The thrid-party app is a point of sale system and the makers of the software have provided a .fxp file that allows us to export product information into an XML format.

The problem that I am running into is that the software has no way to schedule the .fxp file to run at a regular interval which we need to keep that XML file updated.

My question is, can a .fxp file be executed outside of FoxPro?

Alternatively, can I create my own FoxPro application to execute their .fxp file and have it connect to the POS database to perform the export.

Any ideas or alternatives are welcome.

Thanks,
Brian

答:
If you don't have Visual Foxpro available ask the "makers" of the fxp to provide an executable (built in VFP) so that you can run the fxp.

If they are not willing to support you I'll be able to provide a "foxpro scripting host" which is a small runtime environment which can run stand-alone FXPs.

hope this help

OwnerDisplayName: Brian Behm

Title: FoxPro fxp files


问:
Check if T has operator<<
I am writing code to compare to instances of various types. The final comparison function is quite simple - with signature:

```<code>template <typename T>
int not_equal(const T& arg1, const T& arg2) {
    if (arg1 == arg2)
        return 0;

    std::cerr << "Error when comparing" << std::endl;
    return 1;
}
</code>```

Now - I would like to add the actual values being compared in the std::cerr message as:

```<code>std::cerr << "Error when comparing " << arg1 << " != " << arg2 << std::endl;
</code>```

however - many of the classes do not have operator<< - and that is OK. For the classes which do not support operator<< I just want the classname - i.e. the pseudo code should be something like:

```<code>if (supports_operator<<<T>)
    std::cerr << "Error when comparing " << arg1 << " != " << arg2 << std::endl;
else
    std::cerr << "Error when comparing instances of type: " << typeid(arg1).name() << std::endl;
</code>```

Can I have my fictitious supports_operator<<<T>()functionality?

Edit: I am limited to C++17

答:
If you are able to use C++20 and concepts, then you can do something like this:

#include <iostream>
#include <concepts>

template <typename T>
concept Streamable = requires (T x) { std::cout << x; };

struct Foo {};
struct Bar {};

std::ostream& operator<<(std::ostream& os, Foo const& obj) {
    // write obj to stream
    return os;
}

template <Streamable T>
void foo(T const& t) {
    std::cout << t << std::endl;
}

int main() {
    Foo f;
    Bar b;

    foo(f);
    foo(b); // error

    return 0;
}
```

Demo

Title: Check if T has operator<<

Body:
I am writing code to compare to instances of various types. The final comparison function is quite simple - with signature:

template <typename T>
int not_equal(const T& arg1, const T& arg2) {
    if (arg1 == arg2)
        return 0;

    std::cerr << "Error when comparing" << std::endl;
    return 1;
}

Now - I would like to add the actual values being compared in the std::cerr message as:

std::cerr << "Error when comparing " << arg1 << " != " << arg2 << std::endl;

however - many of the classes do not have operator<< - and that is OK. For the classes which do not support operator<< I just want the classname - i.e. the pseudo code should be something like:

if (supports_operator<<<T>)
    std::cerr << "Error when comparing " << arg1 << " != " << arg2 << std::endl;
else
    std::cerr << "Error when comparing instances of type: " << typeid(arg1).name() << std::endl;

Can I have my fictitious supports_operator<<<T>()functionality?

Edit: I am limited to C++17

Body:
If you are able to use C++20 and concepts, then you can do something like this:

#include <iostream>
#include <concepts>

template <typename T>
concept Streamable = requires (T x) { std::cout << x; };

struct Foo {};
struct Bar {};

std::ostream& operator<<(std::ostream& os, Foo const& obj) {
    // write obj to stream
    return os;
}

template <Streamable T>
void foo(T const& t) {
    std::cout << t << std::endl;
}

int main() {
    Foo f;
    Bar b;

    foo(f);
    foo(b); // error

    return 0;
}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:21,endLineNumber:25,positionColumn:21,positionLineNumber:25,selectionStartColumn:21,selectionStartLineNumber:25,startColumn:21,startLineNumber:25),source:'%23include+%3Ciostream%3E%0A%23include+%3Cconcepts%3E%0A%0Atemplate+%3Ctypename+T%3E+%0Aconcept+Streamable+%3D+requires+(T+x)+%7B+std::cout+%3C%3C+x%3B+%7D%3B%0A%0Astruct+Foo+%7B%7D%3B%0Astruct+Bar+%7B%7D%3B%0A%0Astd::ostream%26+operator%3C%3C(std::ostream%26+os,+Foo+const%26+obj)+%7B%0A++++//+write+obj+to+stream%0A++++return+os%3B%0A%7D%0A%0Atemplate+%3CStreamable+T%3E%0Avoid+foo(T+const%26+t)+%7B%0A++++std::cout+%3C%3C+t+%3C%3C+std::endl%3B%0A%7D%0A%0Aint+main()+%7B%0A++++Foo+f%3B%0A++++Bar+b%3B%0A%0A++++foo(f)%3B%0A++++foo(b)%3B+//+error%0A%0A++++return+0%3B+%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:52.637075718015666,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:gsnapshot,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B2a',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+(trunk)+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:37.5,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+gcc+(trunk)',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:47.362924281984334,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">Demo


问:
How can I get XDebug to run with PHPUnit on the CLI in Windows using VSCode?
I ran this command:

"C:\xampp\php\.\php.exe" "C:\xampp\php\phpunit" -d xdebug.profiler_enable=on -d xdebug.idekey=VSCODE

C:\xampp\php\php.ini has the following:

```<code>[XDebug]
zend_extension = "C:\xampp\php\ext\php_xdebug-2.5.0-7.1-vc14.dll"
xdebug.idekey=VSCODE
xdebug.profiler_enable=1
xdebug.default_enable=1
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_autostart=1
</code>```

If I run the command without Listen for XDebug, I will see the following in the command line window:

```<code>Installing...
Running as single site... To run multisite, use -c tests/phpunit/multisite.xml
Not running ajax tests. To execute these, use --group ajax.
Not running ms-files tests. To execute these, use --group ms-files.
Not running external-http tests. To execute these, use --group external-http.
PHPUnit 3.7.21 by Sebastian Bergmann.

Configuration read from C:\xampp\apps\summit\htdocs\wp-content\plugins\hl-market-tracker\phpunit.xml.dist
...
</code>```

I went into VSCode and Listen for XDebug and when I run the command, I see Request 1 and 2 appears in the Call Stack but no unit test got run (it seems to be hung somewhere because Installing... doesn't even show up in the command line window). If I stop listening for Xdebug, I will see read ECONNRESET in the debug console, and then I will see the Running as single site... statement being printed out (but not the Installing... statement)

Questions:

I would like to understand how to get debugging to work when I try to run the unit test?

Why did I see the hung behavior described above? What am I not understanding?

References:

https://pippinsplugins.com/unit-tests-wordpress-plugins-writing-tests/

How can I get XDebug to run with PHPUnit on the CLI?

https://tighten.co/blog/configure-vscode-to-debug-phpunit-tests-with-xdebug

https://xdebug.org/docs/remote

答:
FWIW - setting up the following in launch.json works for me on Ubuntu (with XDebug installed via apt):</p>

```<code>    "configurations": [
    {
        "name": "Launch Unit Tests",
        "type": "php",
        "request": "launch",
        "program": "${workspaceFolder}/vendor/bin/phpunit",
        "cwd": "${workspaceFolder}",
        "env": {
            "XDEBUG_CONFIG": "idekey=VSCODE remote_enable=1 profile_enable=1"
        },
        "args": [
            // "--filter",
            // "testCanCreateValid"
        ],
        "port": 9000
    }
]
</code>```

Body:
I ran this command:

"C:\xampp\php\.\php.exe" "C:\xampp\php\phpunit" -d xdebug.profiler_enable=on -d xdebug.idekey=VSCODE

C:\xampp\php\php.ini has the following:

[XDebug]
zend_extension = "C:\xampp\php\ext\php_xdebug-2.5.0-7.1-vc14.dll"
xdebug.idekey=VSCODE
xdebug.profiler_enable=1
xdebug.default_enable=1
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_autostart=1

If I run the command without Listen for XDebug, I will see the following in the command line window:

Installing...
Running as single site... To run multisite, use -c tests/phpunit/multisite.xml
Not running ajax tests. To execute these, use --group ajax.
Not running ms-files tests. To execute these, use --group ms-files.
Not running external-http tests. To execute these, use --group external-http.
PHPUnit 3.7.21 by Sebastian Bergmann.

Configuration read from C:\xampp\apps\summit\htdocs\wp-content\plugins\hl-market-tracker\phpunit.xml.dist
...

I went into VSCode and Listen for XDebug and when I run the command, I see Request 1 and 2 appears in the Call Stack but no unit test got run (it seems to be hung somewhere because Installing... doesn't even show up in the command line window). If I stop listening for Xdebug, I will see read ECONNRESET in the debug console, and then I will see the Running as single site... statement being printed out (but not the Installing... statement)

Questions:

I would like to understand how to get debugging to work when I try to run the unit test?

Why did I see the hung behavior described above? What am I not understanding?

References:

https://pippinsplugins.com/unit-tests-wordpress-plugins-writing-tests/

How can I get XDebug to run with PHPUnit on the CLI?

https://tighten.co/blog/configure-vscode-to-debug-phpunit-tests-with-xdebug

https://xdebug.org/docs/remote

Body:
FWIW - setting up the following in launch.json works for me on Ubuntu (with XDebug installed via apt):

    "configurations": [
    {
        "name": "Launch Unit Tests",
        "type": "php",
        "request": "launch",
        "program": "${workspaceFolder}/vendor/bin/phpunit",
        "cwd": "${workspaceFolder}",
        "env": {
            "XDEBUG_CONFIG": "idekey=VSCODE remote_enable=1 profile_enable=1"
        },
        "args": [
            // "--filter",
            // "testCanCreateValid"
        ],
        "port": 9000
    }
]


问:
C# wait for process to start
I have 2 programs(client and server) which communicates using ipc. Basically client sends some data at the server and they work at the same computer. I want the client to wait for server process to start if it does not already started but not quite understand how to achieve this. I think of using 2 events(one which is created my client and one created by server) and wrap both calls to waits for these events in critical section. What you will suggest?</p>

答:
How does the IPC work? I assume NamedPipes, but the idea is the same for me. I had to do something like that in the past and did roughly this:

Client starts, connects to IPC server (assuming NamedPipes. Shouldn't matter)

Connection fails, client recovers by triggering a server start (this can be handled in lots of ways, from executing the server binary from a known location to using trigger started services)

Server starts and as one of the first thing claims the IPC address (or a global mutex if you like that one better). If multiple server processes are started from multiple clients, the first one wins and the others just die again.

Client retries after an appropriate time

Title: C# wait for process to start


问:
How do I delete a row from my database based on a post value within the row
I have a dynamic form where users can add rows and submit that data to a database and when users return to the form page the data that was submitted pre-populates the form to which they can update the data or add more rows of data.

If a user wants to delete a row from the database I have a delete button that changes the 'is_active' form value from 'yes' to 'no' for that particular row and when they submit the form, I want to delete the row that has the 'is_active' post value of 'no'.

I am using $wpdb to replace the rows and also to delete them. The code that I have commented out ends up deleting all rows in the table instead of just the ones with the is_active post value of 'no'.

Here is my code:

```<code><?php
    require_once '../../../wp-load.php';

    global $wpdb;
    $newdb = new wpdb( 'user' , 'pass' , 'table' , 'localhost' );

    if(isset($_POST['submit'])) {

        $username = $_POST['username'];
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $county = $_POST['county'];
        $street = $_POST['street'];
        $city = $_POST['city'];
        $ward = $_POST['ward'];
        $precinct = $_POST['precinct'];
        $id = $_POST['id'];
        $is_active = $_POST['is_active'];

        if(is_array($_POST)) {
            foreach($username as $index => $value) {
              if   (in_array("no", $_POST['is_active'], TRUE))
              {
              /*  $newdb->delete( 'member_lists', array( 'id' => $id[$index])); */
                        $newdb->query(
                            $newdb->prepare(
                                    "
                                     DELETE FROM $newdb->member_lists
                                     WHERE id = $id[$index]
                                     AND $is_active[$index] = 'no'
                                    "
                                    )
                        );

                       $newdb->replace( 'member_lists',
                array(
                        'id' => $id[$index],
                        'username' => $value,
                        'first_name' => $first_name[$index],
                        'last_name' => $last_name[$index],
                        'county' => $county[$index],
                        'street' => $street[$index],
                        'city' => $city[$index],
                        'ward' => $ward[$index],
                        'precinct' => $precinct[$index]

                    ),
                    array(
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                    )
);

                $wpdb->show_errors();

              }
                else{
                $newdb->replace( 'member_lists',
                array(
                        'id' => $id[$index],
                        'username' => $value,
                        'first_name' => $first_name[$index],
                        'last_name' => $last_name[$index],
                        'county' => $county[$index],
                        'street' => $street[$index],
                        'city' => $city[$index],
                        'ward' => $ward[$index],
                        'precinct' => $precinct[$index]

                    ),
                    array(
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                    )
);

                $wpdb->show_errors();
                }

            }
        }

    }

?>

</code>```

答:
I might not employ this method but for the sake of answering the question, here is the solution I came up with.

Instead of trying to read the value of "is_active" before insert/update and then deleting the entry from the database, what I did was submit that value to the database and then after my initial 'replace' query, I run a second query where I delete from the database any row where the value of 'is_active' is 'no'.

Seeing as that any row where 'is_active' is marked as 'no' for deletion I don't want it in the database at all so I don't bother with reading the row based on the index.

```<code><?php
    require_once '../../../wp-load.php';

    global $wpdb;
    $newdb = new wpdb( 'user' , 'pass' , 'table' , 'localhost' );

    if(isset($_POST['submit'])) {

        $username = $_POST['username'];
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $county = $_POST['county'];
        $street = $_POST['street'];
        $city = $_POST['city'];
        $ward = $_POST['ward'];
        $precinct = $_POST['precinct'];
        $id = $_POST['id'];
        $is_active = $_POST['is_active'];

        if(is_array($_POST)) {
            foreach($username as $index => $value) {

                $newdb->replace( 'member_lists',
                array(
                        'id' => $id[$index],
                        'username' => $value,
                        'first_name' => $first_name[$index],
                        'last_name' => $last_name[$index],
                        'county' => $county[$index],
                        'street' => $street[$index],
                        'city' => $city[$index],
                        'ward' => $ward[$index],
                        'precinct' => $precinct[$index],
                        'is_active' => $is_active[$index]

                    ),
                    array(
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                    )
);

                $newdb->show_errors();

            }

        }

        if ($newdb) {
$newdb->delete('member_lists', array('is_active' => "no"));
            wp_redirect('http://website.com/home/list-has-been-updated/');

}
    }

?>

</code>```

Body:
I have a dynamic form where users can add rows and submit that data to a database and when users return to the form page the data that was submitted pre-populates the form to which they can update the data or add more rows of data.

If a user wants to delete a row from the database I have a delete button that changes the 'is_active' form value from 'yes' to 'no' for that particular row and when they submit the form, I want to delete the row that has the 'is_active' post value of 'no'.

I am using $wpdb to replace the rows and also to delete them. The code that I have commented out ends up deleting all rows in the table instead of just the ones with the is_active post value of 'no'.

Here is my code:

<?php
    require_once '../../../wp-load.php';

    global $wpdb;
    $newdb = new wpdb( 'user' , 'pass' , 'table' , 'localhost' );

    if(isset($_POST['submit'])) {

        $username = $_POST['username'];
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $county = $_POST['county'];
        $street = $_POST['street'];
        $city = $_POST['city'];
        $ward = $_POST['ward'];
        $precinct = $_POST['precinct'];
        $id = $_POST['id'];
        $is_active = $_POST['is_active'];

        if(is_array($_POST)) {
            foreach($username as $index => $value) {
              if   (in_array("no", $_POST['is_active'], TRUE))
              {
              /*  $newdb->delete( 'member_lists', array( 'id' => $id[$index])); */
                        $newdb->query(
                            $newdb->prepare(
                                    "
                                     DELETE FROM $newdb->member_lists
                                     WHERE id = $id[$index]
                                     AND $is_active[$index] = 'no'
                                    "
                                    )
                        );

                       $newdb->replace( 'member_lists',
                array(
                        'id' => $id[$index],
                        'username' => $value,
                        'first_name' => $first_name[$index],
                        'last_name' => $last_name[$index],
                        'county' => $county[$index],
                        'street' => $street[$index],
                        'city' => $city[$index],
                        'ward' => $ward[$index],
                        'precinct' => $precinct[$index]

                    ),
                    array(
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                    )
);

                $wpdb->show_errors();

              }
                else{
                $newdb->replace( 'member_lists',
                array(
                        'id' => $id[$index],
                        'username' => $value,
                        'first_name' => $first_name[$index],
                        'last_name' => $last_name[$index],
                        'county' => $county[$index],
                        'street' => $street[$index],
                        'city' => $city[$index],
                        'ward' => $ward[$index],
                        'precinct' => $precinct[$index]

                    ),
                    array(
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                    )
);

                $wpdb->show_errors();
                }

            }
        }

    }

?>

Body:
I might not employ this method but for the sake of answering the question, here is the solution I came up with.

Instead of trying to read the value of "is_active" before insert/update and then deleting the entry from the database, what I did was submit that value to the database and then after my initial 'replace' query, I run a second query where I delete from the database any row where the value of 'is_active' is 'no'.

Seeing as that any row where 'is_active' is marked as 'no' for deletion I don't want it in the database at all so I don't bother with reading the row based on the index.

<?php
    require_once '../../../wp-load.php';

    global $wpdb;
    $newdb = new wpdb( 'user' , 'pass' , 'table' , 'localhost' );

    if(isset($_POST['submit'])) {

        $username = $_POST['username'];
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $county = $_POST['county'];
        $street = $_POST['street'];
        $city = $_POST['city'];
        $ward = $_POST['ward'];
        $precinct = $_POST['precinct'];
        $id = $_POST['id'];
        $is_active = $_POST['is_active'];

        if(is_array($_POST)) {
            foreach($username as $index => $value) {

                $newdb->replace( 'member_lists',
                array(
                        'id' => $id[$index],
                        'username' => $value,
                        'first_name' => $first_name[$index],
                        'last_name' => $last_name[$index],
                        'county' => $county[$index],
                        'street' => $street[$index],
                        'city' => $city[$index],
                        'ward' => $ward[$index],
                        'precinct' => $precinct[$index],
                        'is_active' => $is_active[$index]

                    ),
                    array(
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                        '%s',
                    )
);

                $newdb->show_errors();

            }

        }

        if ($newdb) {
$newdb->delete('member_lists', array('is_active' => "no"));
            wp_redirect('http://website.com/home/list-has-been-updated/');

}
    }

?>


问:
Webserver cannot connect to Redis via docker-compose
I am trying to connect to a redis instance on a docker network via a webserver on the same network. My code is in go and I'm using
My docker-compose.yml:

```<code>thor-redis:
    image: redis:5.0.7
    networks:
      - thorcast
    ports:
      - "6380:6379"
    volumes:
      - ./redis.conf:/usr/local/etc/redis.conf
    entrypoint: redis-server /usr/local/etc/redis.conf
thorcast-server:
    build: ../../thorcast-server
    volumes:
      - ../../thorcast-server:/app/thorcast-server
    networks:
      - thorcast
    ports:
      - "8000:8000"
    env_file:
      - ../../thorcast-server/env.list
</code>```

Relevant section of the env.list file:

```<code>REDIS_HOST=thor-redis
REDIS_PORT=6380
REDIS_DB=0
REDIS_PASSWORD=redis_pass
</code>```

The code in my app to connect to redis is:

```<code>a.Redis = redis.NewClient(&redis.Options{
    Addr:       fmt.Sprintf("%s:%s", conf.redisHost, conf.redisPort),
    Password:   conf.redisPassword,
    DB:         conf.redisDb,
})
</code>```

My code for populating conf is:

```<code>type config struct {
    sqlUsername     string
    sqlPassword     string
    sqlHost         string
    sqlPort         string
    sqlDbName       string
    redisPassword   string
    redisHost       string
    redisPort       string
    redisDb         int
}
// method to initialize config struct from environment variables
func (conf *config) configure() {
    conf.sqlUsername = os.Getenv("THORCAST_DB_USERNAME")
    conf.sqlPassword = os.Getenv("THORCAST_DB_PASSWORD")
    conf.sqlHost = os.Getenv("THORCAST_DB_HOST")
    conf.sqlPort = os.Getenv("THORCAST_DB_PORT")
    conf.sqlDbName = os.Getenv("THORCAST_DB_NAME")
    conf.redisPassword = os.Getenv("REDIS_PASSWORD")
    conf.redisHost = os.Getenv("REDIS_HOST")
    conf.redisPort = os.Getenv("REDIS_PORT")
    conf.redisDb, _ = strconv.Atoi(os.Getenv("REDIS_DB"))
}
var conf = config{}

type App struct {
    Router *mux.Router
    Logger http.Handler
    DB     *sql.DB
    Redis  *redis.Client
}
</code>```

In the redis.conf file, no bind IPs are specified, and requirepass is set to the same value as redis_pass. Furthermore, the error I'm seeing on my server is:

```<code>{"error":"dial tcp 172.21.0.5:6380: connect: connection refused"}
</code>```

When I inspect the redis image, I can confirm it has this IP address:

```<code>docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' dev_thor-
redis_1
172.21.0.5
</code>```

When I try to connect off of my local machine via redis-cli, I can access the server without issue. I have googled around to try and find similar issues, but they all seem to be with people trying to access redis via localhost, which I am not trying to do. Any help is greatly appreciated.

答:
You may forgot to link you app with redis from network poitn of view</p>

```<code>    thor-redis:
        image: redis:5.0.7
        networks:
          - thorcast
        ports:
          - "6380:6379"
        volumes:
          - ./redis.conf:/usr/local/etc/redis.conf
        entrypoint: redis-server /usr/local/etc/redis.conf
    thorcast-server:
        build: ../../thorcast-server
        volumes:
          - ../../thorcast-server:/app/thorcast-server
        networks:
          - thorcast
        ports:
          - "8000:8000"
        env_file:
          - ../../thorcast-server/env.list
        links:          # <-- Add this
          - thor-redis  # <-- Add this
</code>```

Body:
I am trying to connect to a redis instance on a docker network via a webserver on the same network. My code is in go and I'm using
My docker-compose.yml:

thor-redis:
    image: redis:5.0.7
    networks:
      - thorcast
    ports:
      - "6380:6379"
    volumes:
      - ./redis.conf:/usr/local/etc/redis.conf
    entrypoint: redis-server /usr/local/etc/redis.conf
thorcast-server:
    build: ../../thorcast-server
    volumes:
      - ../../thorcast-server:/app/thorcast-server
    networks:
      - thorcast
    ports:
      - "8000:8000"
    env_file:
      - ../../thorcast-server/env.list

Relevant section of the env.list file:

REDIS_HOST=thor-redis
REDIS_PORT=6380
REDIS_DB=0
REDIS_PASSWORD=redis_pass

The code in my app to connect to redis is:

a.Redis = redis.NewClient(&redis.Options{
    Addr:       fmt.Sprintf("%s:%s", conf.redisHost, conf.redisPort),
    Password:   conf.redisPassword,
    DB:         conf.redisDb,
})

My code for populating conf is:

type config struct {
    sqlUsername     string
    sqlPassword     string
    sqlHost         string
    sqlPort         string
    sqlDbName       string
    redisPassword   string
    redisHost       string
    redisPort       string
    redisDb         int
}
// method to initialize config struct from environment variables
func (conf *config) configure() {
    conf.sqlUsername = os.Getenv("THORCAST_DB_USERNAME")
    conf.sqlPassword = os.Getenv("THORCAST_DB_PASSWORD")
    conf.sqlHost = os.Getenv("THORCAST_DB_HOST")
    conf.sqlPort = os.Getenv("THORCAST_DB_PORT")
    conf.sqlDbName = os.Getenv("THORCAST_DB_NAME")
    conf.redisPassword = os.Getenv("REDIS_PASSWORD")
    conf.redisHost = os.Getenv("REDIS_HOST")
    conf.redisPort = os.Getenv("REDIS_PORT")
    conf.redisDb, _ = strconv.Atoi(os.Getenv("REDIS_DB"))
}
var conf = config{}

type App struct {
    Router *mux.Router
    Logger http.Handler
    DB     *sql.DB
    Redis  *redis.Client
}

In the redis.conf file, no bind IPs are specified, and requirepass is set to the same value as redis_pass. Furthermore, the error I'm seeing on my server is:

{"error":"dial tcp 172.21.0.5:6380: connect: connection refused"}

When I inspect the redis image, I can confirm it has this IP address:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' dev_thor-
redis_1
172.21.0.5

When I try to connect off of my local machine via redis-cli, I can access the server without issue. I have googled around to try and find similar issues, but they all seem to be with people trying to access redis via localhost, which I am not trying to do. Any help is greatly appreciated.

Body:
You may forgot to link you app with redis from network poitn of view

    thor-redis:
        image: redis:5.0.7
        networks:
          - thorcast
        ports:
          - "6380:6379"
        volumes:
          - ./redis.conf:/usr/local/etc/redis.conf
        entrypoint: redis-server /usr/local/etc/redis.conf
    thorcast-server:
        build: ../../thorcast-server
        volumes:
          - ../../thorcast-server:/app/thorcast-server
        networks:
          - thorcast
        ports:
          - "8000:8000"
        env_file:
          - ../../thorcast-server/env.list
        links:          # <-- Add this
          - thor-redis  # <-- Add this


问:
Spreading data from a column with class and variable intermixed
I have a dataset in SAS in the following format

```<code>value   animal
---------------
NA       Felidae
5        Lion
3        Cat
NA       Canidae
1        Dog
2        Wolf
</code>```

I would like to transform this into the following, using either SAS directly, or proc sql;

```<code>group    value  animal
----------------------
Felidae    5     Lion
Felidae    3     Cat
Canidae    1     Dog
Canidae    2     Wolf
</code>```

My first through was to peek at entries further down the list when value == NA, until we reach another NA. Then we label all the animals in-between with the animal that had the first NA. I would be familiar doing this in python or R, but I'm quite new to SAS and SQL. Of course, I'm aiming to do this as generally as possible without any hard-codings :)

Thanks!

答:
Data step using retain statement:

```<code>data want;
   set have;
   retain group;
   if value = . then group=animal;
   else output;
run;
</code>```

Output:

```<code>+-------+--------+---------+
| value | animal |  group  |
+-------+--------+---------+
|     5 | Lion   | Felidae |
|     3 | Cat    | Felidae |
|     1 | Dog    | Canidae |
|     2 | Wolf   | Canidae |
+-------+--------+---------+
</code>```

Body:
I have a dataset in SAS in the following format

value   animal
---------------
NA       Felidae
5        Lion
3        Cat
NA       Canidae
1        Dog
2        Wolf

I would like to transform this into the following, using either SAS directly, or proc sql;

group    value  animal
----------------------
Felidae    5     Lion
Felidae    3     Cat
Canidae    1     Dog
Canidae    2     Wolf

My first through was to peek at entries further down the list when value == NA, until we reach another NA. Then we label all the animals in-between with the animal that had the first NA. I would be familiar doing this in python or R, but I'm quite new to SAS and SQL. Of course, I'm aiming to do this as generally as possible without any hard-codings :)

Thanks!

Body:
Data step using retain statement:

data want;
   set have;
   retain group;
   if value = . then group=animal;
   else output;
run;

Output:

+-------+--------+---------+
| value | animal |  group  |
+-------+--------+---------+
|     5 | Lion   | Felidae |
|     3 | Cat    | Felidae |
|     1 | Dog    | Canidae |
|     2 | Wolf   | Canidae |
+-------+--------+---------+


问:
INSERT INTO based on SELECT and versioned record
I have a table that contains the current state of employees like below :

```<code> SELECT EmployeeId ,OfficeId from EmpCurrent
</code>```

The output is like below :

```<code>EmployeeId OfficeId
54          67
64          57
89          23
</code>```

And I have another table containing the full history for an employee except for OfficeId which isn't historised (I added the column OfficeId which is NULL to insert from EmpCurrent) :

```<code>SELECT EmployeeId ,Func AS [Function],OfficeId,Version from EmpHistory
</code>```

The output is like below for EmployeeId=54:

```<code>EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   NULL     3
</code>```

I want to get the OfficeId from EmpCurrent and insert it in EmpHistory in the last Version(max version) of the each Employee, my output will be like below :

```<code>EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   67       3
</code>```

答:
```<code>;WITH CTE_EMP
AS
(
    SELECT
        EH.EmployeeId
        ,Version        = MAX(Version)
    FROM
        EmpHistory AS EH
    GROUP BY
        EH.EmployeeId
)
select
     EH.EmployeeId
    ,EH.Func
    ,OfficeId       = CASE WHEN CTE.Version = EH.Version THEN EC.OfficeId END
    ,EH.Version
from
    EmpHistory AS EH
    LEFT OUTER JOIN EmpCurrent AS EC ON EC.EmployeeId = EH.EmployeeId
    LEFT OUTER JOIN CTE_EMP AS CTE ON CTE.EmployeeId = EH.EmployeeId
</code>```

Body:
I have a table that contains the current state of employees like below :

 SELECT EmployeeId ,OfficeId from EmpCurrent

The output is like below :

EmployeeId OfficeId
54          67
64          57
89          23

And I have another table containing the full history for an employee except for OfficeId which isn't historised (I added the column OfficeId which is NULL to insert from EmpCurrent) :

SELECT EmployeeId ,Func AS [Function],OfficeId,Version from EmpHistory

The output is like below for EmployeeId=54:

EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   NULL     3

I want to get the OfficeId from EmpCurrent and insert it in EmpHistory in the last Version(max version) of the each Employee, my output will be like below :

EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   67       3


问:
After Add the Record Alert Message is not displayed Servlet Ajax
After Add the Record  Record is insert into the database successfully but Alert Message is not displayed using Servlet Ajax. i am tring this since yesterday i didn't solve the problem yet.  what i tried so far i attached below. i don't know what was the problem is.i need to display alert message after add the record thats what i need.

Form

```<code><div class="col-sm-4">
<form class="card" id="frmProject">
    <div class="bg-2form-group" align="left">
        <label class="form-label">First Name</label>
        <input type="text" class="form-control" placeholder="First Name" id="fname" name="fname" size="30px"  required>

    </div>
     <div class="bg-2form-group" align="left">
        <label class="form-label">Last Name</label>
        <input type="text" class="form-control" placeholder="Last Name" id="lname" name="lname" size="30px"  required>

    </div>

    <div class="card" align="right">

        <button type="button" id="save" class="btn btn-info" onclick="addProject()">Add
        </button>
        <button type="button" id="clear" class="btn btn-warning" onclick="reSet()">Reset</button>
    </div>
</form>
</code>```

Jquery

```<code>var isNew = true;
            function addProject()
            {
                if($("#frmProject").valid())
                {
                    var url="";
                    var data= "";
                    var method;

                    if(isNew==true)
                    {
                        url = 'add';
                        data = $("#frmProject").serialize();
                        method = 'POST'
                    }
                    else
                    {
                        url = 'update';
                        data = $("#frmProject").serialize() + "&catid=" + catid;
                        method = 'POST'
                        console.log(data);
                    }
                    $.ajax({
                        type: method,
                        url : url,
                        dataType: 'JSON',
                        data : data,

                        success:function(data)
                        {
                            if(isNew ==true)
                            {
                                alert("Record Adddeddd");
                            }
                            else
                            {
                                 alert("Record Updatee");
                            }
                        }
                    });
                }
            }
</code>```

Servlet Page

```<code>Connection con;
    PreparedStatement pst;
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();
    String fname = request.getParameter("fname");
    String lname = request.getParameter("lname");

         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection("jdbc:mysql://localhost/details", "root", "");
         String query = "insert into record(firstname,lastname)values(?,?)";
         pst = con.prepareStatement(query);
         pst.setString(1, fname);
         pst.setString(2, lname);
         pst.executeUpdate();

         String greetings = "Record Addeddddd ";
         response.setContentType("text/plain");
         response.getWriter().write(greetings);
</code>```

答:
$.ajax({
                        type: method,
                        url : url,
                       **// dataType: 'JSON',
                        data : data,
                        success:function(data)
                        {
                            if(isNew ==true)
                            {
                                alert("Record Adddeddd");
                            }
                            else
                            {
                                 alert("Record Updatee");

                            }

                        }

                    });**

please try to remove // dataType: 'JSON' and run your code.

Body:
After Add the Record  Record is insert into the database successfully but Alert Message is not displayed using Servlet Ajax. i am tring this since yesterday i didn't solve the problem yet.  what i tried so far i attached below. i don't know what was the problem is.i need to display alert message after add the record thats what i need.

Form

<form class="card" id="frmProject">

        First Name
        <input type="text" class="form-control" placeholder="First Name" id="fname" name="fname" size="30px"  required>

        Last Name
        <input type="text" class="form-control" placeholder="Last Name" id="lname" name="lname" size="30px"  required>

        <button type="button" id="save" class="btn btn-info" onclick="addProject()">Add
        </button>
        <button type="button" id="clear" class="btn btn-warning" onclick="reSet()">Reset</button>

</form>

Jquery

var isNew = true;
            function addProject()
            {
                if($("#frmProject").valid())
                {
                    var url="";
                    var data= "";
                    var method;

                    if(isNew==true)
                    {
                        url = 'add';
                        data = $("#frmProject").serialize();
                        method = 'POST'
                    }
                    else
                    {
                        url = 'update';
                        data = $("#frmProject").serialize() + "&catid=" + catid;
                        method = 'POST'
                        console.log(data);
                    }
                    $.ajax({
                        type: method,
                        url : url,
                        dataType: 'JSON',
                        data : data,

                        success:function(data)
                        {
                            if(isNew ==true)
                            {
                                alert("Record Adddeddd");
                            }
                            else
                            {
                                 alert("Record Updatee");
                            }
                        }
                    });
                }
            }

Servlet Page

Connection con;
    PreparedStatement pst;
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();
    String fname = request.getParameter("fname");
    String lname = request.getParameter("lname");

         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection("jdbc:mysql://localhost/details", "root", "");
         String query = "insert into record(firstname,lastname)values(?,?)";
         pst = con.prepareStatement(query);
         pst.setString(1, fname);
         pst.setString(2, lname);
         pst.executeUpdate();

         String greetings = "Record Addeddddd ";
         response.setContentType("text/plain");
         response.getWriter().write(greetings);


问:
Getting Semester Averages with Grades using files in Python
I want to write code that will take a file of grades and return an average of it all, so homework average, project average, quiz average, and semester average. In the file it would have a column at the start which would be the "legend" to the code. Here's an example of what the grade file would look like:

```<code>last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
#It won't also be in this order, that's what makes this hard!
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88
#Not a real name lol, there would also be A LOT more names and grades
</code>```

I can't figure out how to make it iterate through the legend column and the grades column to correctly grade the file. Here's the formula for grading:

```<code>semester average = homework average * 0.2 + quiz average * 0.2 + project average * 0.6.
</code>```

Here's what I have so far. I'm terrible with files so I only know how to call a column.

```<code>def start():
  gb_data = open('gb_data.txt','r')
  header = gb_data.readline()
  print(header.strip())
</code>```

the strip() at the end would get rid of the \n that happens when you change lines. This prints the first column of the file but I want to iterate through it and identify the legend, not just print it. Here's what the return file would look like:

```<code>Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21
</code>```

Please help! This is NOT homework and is simply a project to understand files better, my name is Scarlett btw.

答:
You probably want to have a look at pandas. It's best to give your columns unique column names, though.

import pandas as pd

def get_avg(row):
    hw_avg = (row['hw_1'] + row['hw_1'] + row['hw_1']) / 3
    # fill in as needed
    quiz_avg = ...
    proj_avg = ...
    return hw_avg * 0.2 + quiz_avg * 0.2 + proj_avg * 0.6

# read your data
df = pd.read_csv('your-file.csv')
# 'apply' a function to each row (axis=1) in a dataframe,
# add all results to a new column called 'semester_avg'
df['semester_avg'] = df.apply(get_avg, axis=1)
```

Body:
I want to write code that will take a file of grades and return an average of it all, so homework average, project average, quiz average, and semester average. In the file it would have a column at the start which would be the "legend" to the code. Here's an example of what the grade file would look like:

last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
#It won't also be in this order, that's what makes this hard!
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88
#Not a real name lol, there would also be A LOT more names and grades

I can't figure out how to make it iterate through the legend column and the grades column to correctly grade the file. Here's the formula for grading:

semester average = homework average * 0.2 + quiz average * 0.2 + project average * 0.6.

Here's what I have so far. I'm terrible with files so I only know how to call a column.

def start():
  gb_data = open('gb_data.txt','r')
  header = gb_data.readline()
  print(header.strip())

the strip() at the end would get rid of the \n that happens when you change lines. This prints the first column of the file but I want to iterate through it and identify the legend, not just print it. Here's what the return file would look like:

Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21

Please help! This is NOT homework and is simply a project to understand files better, my name is Scarlett btw.


问:
Django: relation "django_site" does not exist
I am running a test django server on aws and I just installed django-userena and when I try to signup a user upon clicking submit, I get the following message:

relation "django_site" does not exist LINE 1:
  ..."django_site"."domain", "django_site"."name" FROM "django_si...

I am not really sure what went wrong here. I did some researching and added "    'django.contrib.sites'," to my installed apps, but I am still getting the error. I will there is an extra step I am missing. Any suggestions or advice?

答:
I experienced the same problem with creating a new empty database for my project (which uses zinnia)

Running 'manage migrate site' before 'manage migrate' did not solve anything. It seems that the complete project was loaded before any table creating was done.

I resolved to catching the errors that importing the zinnia releated app produced.

e.g.:
in the urls.py of the app

```<code>urlpatterns = None
app_name = 'something'

try:
    from .views import MyEntryCreate

    urlpatterns = [

    url(r'^blogentry/create/$',
        login_required(MyEntryCreate.as_view()),
        name='zinnia_entry-add'),

    ]
except Exception as e:
    logger.error(app_name+" Error urls: "+str(e))
    urlpatterns = []
</code>```

Had to do something like that elsewhere in that app, and 'manage migrate' worked again.

Body:
I experienced the same problem with creating a new empty database for my project (which uses zinnia)

Running 'manage migrate site' before 'manage migrate' did not solve anything. It seems that the complete project was loaded before any table creating was done.

I resolved to catching the errors that importing the zinnia releated app produced.

e.g.:
in the urls.py of the app

urlpatterns = None
app_name = 'something'

try:
    from .views import MyEntryCreate

    urlpatterns = [

    url(r'^blogentry/create/$',
        login_required(MyEntryCreate.as_view()),
        name='zinnia_entry-add'),

    ]
except Exception as e:
    logger.error(app_name+" Error urls: "+str(e))
    urlpatterns = []

Had to do something like that elsewhere in that app, and 'manage migrate' worked again.