问:
Swagger/OpenAPI 3.0 generation - Endpoint with generic list from an interface does not show up in documentation
I'm trying to generate a API documentation/swagger client for a Java EE application using Swagger / OpenAPI 3.0, but one method keeps missing in the documentation.
I created a sample project to clarify my problem:

New, less complex example:

I got an Interface with a List as a parameter for my REST endpoint:

```<code>    package de.rockbunker.api;

    import javax.ws.rs.core.Response;
    import java.util.List;

    public interface Pong<T> {
        Response pongList(List<T> pongs);
    }

</code>```

I'll implement this service and add swagger annotations:

```<code>
    package de.rockbunker.api;

    import io.swagger.v3.oas.annotations.Operation;

    import javax.enterprise.context.ApplicationScoped;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.core.Response;
    import java.util.List;

    @ApplicationScoped
    @Path("")
    public class PingService implements Pong<String> {

        // Does not show up in documentation!?
        @POST
        @Path("pongList")
        @Operation(summary = "Pong List in Interface", tags = "Pong")
        @Override
        public Response pongList(List<String> pongs) {
            return Response.ok().build();
        }

    }

</code>```

I try to generate a openapi documentation using the maven plugin (full configuration see below):

```<code>            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <version>2.1.1</version>
</code>```

But the generated documentation remains empty, the endpoint does not show up:

```<code>openapi: 3.0.1
</code>```

More complex example

My rest endpoint implements a interface with a type parameter. I tried to use this parameter in several ways, resulting in this interface

```<code>public interface Pong<T> {
    Response pongList(List<T> pongs);

    Response pongArray(T[] pongs);

    Response justPong(T pong);

    Response pongNoTypeParameter(List<Integer> intPongs);
}
</code>```

The service that implements the interface looks like this:

```<code>
    package de.rockbunker.api;

    import io.swagger.v3.oas.annotations.Operation;
    import io.swagger.v3.oas.annotations.Parameter;
    import io.swagger.v3.oas.annotations.media.Schema;

    import javax.enterprise.context.ApplicationScoped;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.core.Response;
    import java.util.List;

    @ApplicationScoped
    @Path("")
    public class PingService implements Pong<String>{

        // Works
        @GET
        @Path("ping")
        @Operation(summary = "Just ping", tags = "Ping")
        public Response ping() {
            return Response.ok("Ping").build();
        }

        // Does not show up
        @POST
        @Path("pongListInInterface")
        @Operation(summary = "Pong List in Interface", tags = "Pong")
        @Override
        public Response pongList(List<String> pongs) {
            return Response.ok().build();
        }

        // Works
        @POST
        @Path("pongArrayInInterface")
        @Operation(summary = "Pong Array in Interface", tags = "Pong")
        @Override
        public Response pongArray(String[] pongs) {
            return Response.ok().build();
        }

        // Works
        @GET
        @Path("pong")
        @Operation(summary = "Just pong", tags = "Pong")
        @Override
        public Response justPong(String pong) {
            return Response.ok().build();
        }

        // Works
        @GET
        @Path("intPong")
        @Operation(summary = "Just Integer pongs", tags = "Pong")
        @Override
        public Response pongNoTypeParameter(List<Integer> intPongs) {
            return Response.ok().build();
        }

        // Works
        @POST
        @Path("pongListNoInterface")
        @Operation(summary = "Pong List no Interface", tags = "Pong")
        public Response pongListNoInterface(List<String> pongs) {
            return Response.ok().build();
        }
    }

</code>```

The openapi docmentation is generated, using the Maven plugin io.swagger.core.v3.swagger-annotations in version 2.1.1, resulting in a documentation that contains every method, but Response pongList(List<T> pongs); Every other use of that type parameter somehow works nicely, only when I use the type parameter as the type of a list I can't get it to show up.

```<code>openapi: 3.0.1
paths:
  /pong:
    get:
      tags:
      - Pong
      summary: Just pong
      operationId: justPong
      requestBody:
        content:
          '*/*':
            schema:
              type: string
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /pongArrayInInterface:
    post:
      tags:
      - Pong
      summary: Pong Array in Interface
      operationId: pongArray
      requestBody:
        content:
          '*/*':
            schema:
              type: array
              items:
                type: string
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /ping:
    get:
      tags:
      - Ping
      summary: Just ping
      operationId: ping
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /intPong:
    get:
      tags:
      - Pong
      summary: Just Integer pongs
      operationId: pongNoTypeParameter
      requestBody:
        content:
          '*/*':
            schema:
              type: array
              items:
                type: integer
                format: int32
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /pongListNoInterface:
    post:
      tags:
      - Pong
      summary: Pong List no Interface
      operationId: pongListNoInterface
      requestBody:
        content:
          '*/*':
            schema:
              type: array
              items:
                type: string
      responses:
        default:
          description: default response
          content:
            '*/*': {}
</code>```

Plugin configuration:

```<code><plugin>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <outputFileName>openapi</outputFileName>
                <outputPath>${project.build.directory}/${project.artifactId}-${project.version}</outputPath>
                <outputFormat>JSONANDYAML</outputFormat>
                <resourcePackages>
                    <package>de.rockbunker.api</package>
                </resourcePackages>
                <prettyPrint>true</prettyPrint>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>resolve</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

Complete pom.xml

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

    <groupId>de.rock-bunker</groupId>
    <artifactId>swagger-ui-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jackson2-provider -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson2-provider</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.swagger.core.v3/swagger-jaxrs2 -->
<!--        <dependency>-->
<!--            <groupId>io.swagger.core.v3</groupId>-->
<!--            <artifactId>swagger-jaxrs2</artifactId>-->
<!--            <version>2.1.1</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>2.1.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.googlecode.maven-download-plugin</groupId>
                <artifactId>download-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <id>swagger-ui</id>
                        <goals>
                            <goal>wget</goal>
                        </goals>
                        <configuration>
                            <url>https://github.com/swagger-api/swagger-ui/archive/master.tar.gz</url>
                            <unpack>true</unpack>
                            <outputDirectory>${project.build.directory}</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${project.build.directory}/swagger-ui-master/dist</directory>

                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <outputFileName>openapi</outputFileName>
                <outputPath>${project.build.directory}/${project.artifactId}-${project.version}</outputPath>
                <outputFormat>JSONANDYAML</outputFormat>
                <resourcePackages>
                    <package>de.rockbunker.api</package>
                </resourcePackages>
                <prettyPrint>true</prettyPrint>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>resolve</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        </plugins>
    </build>
</project>
</code>```

I dont quite get it. Why is the method Response pongList(List<T> pongs); missing in the documentation? Maybe you can tell me :-).

Greetings!

答:
You have to add Swagger-ui too </p>

```<code>   <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
</code>```

Body:
I'm trying to generate a API documentation/swagger client for a Java EE application using Swagger / OpenAPI 3.0, but one method keeps missing in the documentation.
I created a sample project to clarify my problem:

New, less complex example:

I got an Interface with a List as a parameter for my REST endpoint:

    package de.rockbunker.api;

    import javax.ws.rs.core.Response;
    import java.util.List;

    public interface Pong<T> {
        Response pongList(List<T> pongs);
    }

I'll implement this service and add swagger annotations:

    package de.rockbunker.api;

    import io.swagger.v3.oas.annotations.Operation;

    import javax.enterprise.context.ApplicationScoped;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.core.Response;
    import java.util.List;

    @ApplicationScoped
    @Path("")
    public class PingService implements Pong<String> {

        // Does not show up in documentation!?
        @POST
        @Path("pongList")
        @Operation(summary = "Pong List in Interface", tags = "Pong")
        @Override
        public Response pongList(List<String> pongs) {
            return Response.ok().build();
        }

    }

I try to generate a openapi documentation using the maven plugin (full configuration see below):

            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <version>2.1.1</version>

But the generated documentation remains empty, the endpoint does not show up:

openapi: 3.0.1

More complex example

My rest endpoint implements a interface with a type parameter. I tried to use this parameter in several ways, resulting in this interface

public interface Pong<T> {
    Response pongList(List<T> pongs);

    Response pongArray(T[] pongs);

    Response justPong(T pong);

    Response pongNoTypeParameter(List<Integer> intPongs);
}

The service that implements the interface looks like this:

    package de.rockbunker.api;

    import io.swagger.v3.oas.annotations.Operation;
    import io.swagger.v3.oas.annotations.Parameter;
    import io.swagger.v3.oas.annotations.media.Schema;

    import javax.enterprise.context.ApplicationScoped;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.core.Response;
    import java.util.List;

    @ApplicationScoped
    @Path("")
    public class PingService implements Pong<String>{

        // Works
        @GET
        @Path("ping")
        @Operation(summary = "Just ping", tags = "Ping")
        public Response ping() {
            return Response.ok("Ping").build();
        }

        // Does not show up
        @POST
        @Path("pongListInInterface")
        @Operation(summary = "Pong List in Interface", tags = "Pong")
        @Override
        public Response pongList(List<String> pongs) {
            return Response.ok().build();
        }

        // Works
        @POST
        @Path("pongArrayInInterface")
        @Operation(summary = "Pong Array in Interface", tags = "Pong")
        @Override
        public Response pongArray(String[] pongs) {
            return Response.ok().build();
        }

        // Works
        @GET
        @Path("pong")
        @Operation(summary = "Just pong", tags = "Pong")
        @Override
        public Response justPong(String pong) {
            return Response.ok().build();
        }

        // Works
        @GET
        @Path("intPong")
        @Operation(summary = "Just Integer pongs", tags = "Pong")
        @Override
        public Response pongNoTypeParameter(List<Integer> intPongs) {
            return Response.ok().build();
        }

        // Works
        @POST
        @Path("pongListNoInterface")
        @Operation(summary = "Pong List no Interface", tags = "Pong")
        public Response pongListNoInterface(List<String> pongs) {
            return Response.ok().build();
        }
    }

The openapi docmentation is generated, using the Maven plugin io.swagger.core.v3.swagger-annotations in version 2.1.1, resulting in a documentation that contains every method, but Response pongList(List<T> pongs); Every other use of that type parameter somehow works nicely, only when I use the type parameter as the type of a list I can't get it to show up.

openapi: 3.0.1
paths:
  /pong:
    get:
      tags:
      - Pong
      summary: Just pong
      operationId: justPong
      requestBody:
        content:
          '*/*':
            schema:
              type: string
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /pongArrayInInterface:
    post:
      tags:
      - Pong
      summary: Pong Array in Interface
      operationId: pongArray
      requestBody:
        content:
          '*/*':
            schema:
              type: array
              items:
                type: string
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /ping:
    get:
      tags:
      - Ping
      summary: Just ping
      operationId: ping
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /intPong:
    get:
      tags:
      - Pong
      summary: Just Integer pongs
      operationId: pongNoTypeParameter
      requestBody:
        content:
          '*/*':
            schema:
              type: array
              items:
                type: integer
                format: int32
      responses:
        default:
          description: default response
          content:
            '*/*': {}
  /pongListNoInterface:
    post:
      tags:
      - Pong
      summary: Pong List no Interface
      operationId: pongListNoInterface
      requestBody:
        content:
          '*/*':
            schema:
              type: array
              items:
                type: string
      responses:
        default:
          description: default response
          content:
            '*/*': {}

Plugin configuration:

<plugin>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <outputFileName>openapi</outputFileName>
                <outputPath>${project.build.directory}/${project.artifactId}-${project.version}</outputPath>
                <outputFormat>JSONANDYAML</outputFormat>
                <resourcePackages>
                    <package>de.rockbunker.api</package>
                </resourcePackages>
                <prettyPrint>true</prettyPrint>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>resolve</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Complete pom.xml

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

    <groupId>de.rock-bunker</groupId>
    <artifactId>swagger-ui-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson2-provider</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>2.1.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.googlecode.maven-download-plugin</groupId>
                <artifactId>download-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <id>swagger-ui</id>
                        <goals>
                            <goal>wget</goal>
                        </goals>
                        <configuration>
                            <url>https://github.com/swagger-api/swagger-ui/archive/master.tar.gz</url>
                            <unpack>true</unpack>
                            <outputDirectory>${project.build.directory}</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${project.build.directory}/swagger-ui-master/dist</directory>

                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <outputFileName>openapi</outputFileName>
                <outputPath>${project.build.directory}/${project.artifactId}-${project.version}</outputPath>
                <outputFormat>JSONANDYAML</outputFormat>
                <resourcePackages>
                    <package>de.rockbunker.api</package>
                </resourcePackages>
                <prettyPrint>true</prettyPrint>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>resolve</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        </plugins>
    </build>
</project>

I dont quite get it. Why is the method Response pongList(List<T> pongs); missing in the documentation? Maybe you can tell me :-).

Greetings!

Body:
You have to add Swagger-ui too

   <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>


来源: stackexchange

问:
TypeError: 'last' only supports a DatetimeIndex index
```<code>Ship_Date        Id

2019-10-29       i1
2019-10-29       i2
2019-10-28       i3
2019-10-28       i4

2 years data
</code>```

```<code>df_updated=df.sort_values(by="Date", ascending=False).set_index("Date").last("2M")
</code>```

When I am trying to execute about piece of code getting error like,

" TypeError: 'last' only supports a DatetimeIndex index "

Any help would be appreciate
Thanks

答:
Date is not a datetime object. You need to cast to datetime first with pd.to_datetime:

```<code>df['Date'] = pd.to_datetime(df.Date)
df.sort_values(by="Date", ascending=False).set_index("Date").last("2M")

           Id
Date
2019-10-29  i1
2019-10-29  i2
2019-10-28  i3
2019-10-28  i4
</code>```

Or you could also do:

```<code>df.index = pd.DatetimeIndex(df.pop('Date'))
df.sort_index().last('2M')

           Id
Date
2019-10-29  i1
2019-10-29  i2
2019-10-28  i3
2019-10-28  i4
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Ship_Date        Id

2019-10-29       i1
2019-10-29       i2
2019-10-28       i3
2019-10-28       i4

2 years data

df_updated=df.sort_values(by="Date", ascending=False).set_index("Date").last("2M")

When I am trying to execute about piece of code getting error like,

" TypeError: 'last' only supports a DatetimeIndex index "

Any help would be appreciate
Thanks

Body:
Date is not a datetime object. You need to cast to datetime first with pd.to_datetime:

df['Date'] = pd.to_datetime(df.Date)
df.sort_values(by="Date", ascending=False).set_index("Date").last("2M")

           Id
Date
2019-10-29  i1
2019-10-29  i2
2019-10-28  i3
2019-10-28  i4

Or you could also do:

df.index = pd.DatetimeIndex(df.pop('Date'))
df.sort_index().last('2M')

           Id
Date
2019-10-29  i1
2019-10-29  i2
2019-10-28  i3
2019-10-28  i4


问:
Adjust div height to div parent's
I'm designing a nav panel and I need to adjust the different option's styles to the parent div. For example, I need to adjust the background color of the options to the parent div (Paint the color in the full height of the parent div).

This is the code:

```<code><div class="text-center text-muted"> <div class="container">
 <div class="card">
  <div class="card-header" style="background-color: #e9ecef;">
   <div class="row mt8" id="nav_panel">
    <div class="col-md-2" id="nav_panel_monday" style="background-color: rgb(0, 160, 157);">
    <a id="nav_href_monday" href="#" style="color: white;">Monday</a>
   </div>
   <div class="col-md-2" id="nav_panel_tuesday">
    <a id="nav_href_tuesday" href="#">Tuesday</a>
   </div>
   <div class="col-md-2" id="nav_panel_wednesday">
    <a id="nav_href_wednesday" href="#">Wednesday</a>
   </div>
   <div class="col-md-2" id="nav_panel_thursday">
    <a id="nav_href_thursday" href="#">Thursday</a>
   </div>
   <div class="col-md-2" id="nav_panel_friday">
    <a id="nav_href_friday" href="#">Friday</a>
   </div>
  </div>
 </div>
 <div class="card-body">
  <div id="div_hidden_monday"></div>
  <div id="div_hidden_tuesday" style="display: none;"></div>
  <div id="div_hidden_wednesday" style="display: none;"></div>
  <div id="div_hidden_thursday" style="display: none;"></div>
  <div id="div_hidden_friday" style="display: none;"></div>
 </div>
 </div>
</div>
</div>
</code>```

```<code>.container {
    width: 100%;
    padding-right: 0;
    padding-left: 0;
    margin-right: auto;
    margin-left: auto;
}
.card {
    position: relative;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #FFFFFF;
    background-clip: border-box;
    border: 1px solid rgba(0, 0, 0, 0.125);
    border-radius: 0.25rem;
}
.card-header {
    padding: 0.75rem 1.25rem;
    margin-bottom: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
#nav_panel {
    background-color: #e9ecef;
    padding-right: 0;
    padding-left: 0;
    border-radius: 5px;
}
.col-md-2 {
    position: relative;
    width: 100%;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}
</code>```

Any suggestion? Thanks for reading!

答:
I think, you need to remove padding of the .card-header and add padding to the child elements. Like this
https://jsfiddle.net/bhusalhari99/sruLkt2b/3/

hope it will works for you.

Title: Adjust div height to div parent's

Body:
I'm designing a nav panel and I need to adjust the different option's styles to the parent div. For example, I need to adjust the background color of the options to the parent div (Paint the color in the full height of the parent div).

This is the code:

    Monday

    Tuesday

    Wednesday

    Thursday

    Friday

.container {
    width: 100%;
    padding-right: 0;
    padding-left: 0;
    margin-right: auto;
    margin-left: auto;
}
.card {
    position: relative;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #FFFFFF;
    background-clip: border-box;
    border: 1px solid rgba(0, 0, 0, 0.125);
    border-radius: 0.25rem;
}
.card-header {
    padding: 0.75rem 1.25rem;
    margin-bottom: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
#nav_panel {
    background-color: #e9ecef;
    padding-right: 0;
    padding-left: 0;
    border-radius: 5px;
}
.col-md-2 {
    position: relative;
    width: 100%;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}

Any suggestion? Thanks for reading!


问:
FERNET_KEY configuration is missing when creating a new environment with the same DAGS
I'm using Composer (Airflow) in Google Cloud. I want to create a new environment and take my same DAGs and Variables from the old environment into the new one.

To accomplish this I do the following:

I check several of my variables and export them to a JSON file.

In my new environment I import this same JSON file.

I use gsutil and upload my same DAGs to the new environment

However, in the new environment, all of my DAGs are breaking, due to a FERNET_KEY configuration is missing. My best guess is that this is related to importing my variables that were encrypted using a separate Fernet key but I'm unsure.

Has anyone encountered this issue before? If so, how did you fix it?

答:
We got the same error about FERNET_KEYs. I think there is a bug in new version (composer-1.9.0). They say 'The Fernet Key is now stored in Kubernetes Secrets instead of the Config Map.'
Even if re-enter your connections again, they are not working no.

They already fix the issue in version 1.9.1:

https://cloud.google.com/composer/docs/release-notes


问:
How create combined cucumber plugin report from several reports produced in parallel by maven surefire plugin?
I am required to run cucumber tests in parallel (by using maven surefire multiple jvms, forkCount) -
and the resultant report to be equivalent to a report created by running the tests sequentially.

I am using cucumber v3.
cucumber v4 allows tests to be run in parallel using a single runner with a combined resultant report- however my attempts with v4 have not enabled me to run multiple JVMs with a single runner / produce a single report.

Can you clarify/advise whether there is an alternative/simpler method of doing this to the below? i.e.
is it necessary to create the individual reports and merge them?
Can you clarify that cucumber-jvm 4 does not allow forking of multiple jvms to produce a single report?
The command I have used to run the tests sequentially is:

```<code>mvn test -Dcucumber.options="--plugin junit:target/report.xml --plugin json:target/report.json"
</code>```

In order to run tests in parallel I have created several testrunners each running in a different jvm and
each running several features and outputting (using the report plugins) to different xml and json reports.

In order to combine the reports I am intending to merge the individual xml and json reports.

答:
My Cluecumber Report plugin can actually do this as it merges all existing Cucumber json files into one report.
https://github.com/trivago/cluecumber-report-plugin</p>

Body:
I am required to run cucumber tests in parallel (by using maven surefire multiple jvms, forkCount) -
and the resultant report to be equivalent to a report created by running the tests sequentially.

I am using cucumber v3.
cucumber v4 allows tests to be run in parallel using a single runner with a combined resultant report- however my attempts with v4 have not enabled me to run multiple JVMs with a single runner / produce a single report.

Can you clarify/advise whether there is an alternative/simpler method of doing this to the below? i.e.
is it necessary to create the individual reports and merge them?
Can you clarify that cucumber-jvm 4 does not allow forking of multiple jvms to produce a single report?
The command I have used to run the tests sequentially is:

mvn test -Dcucumber.options="--plugin junit:target/report.xml --plugin json:target/report.json"

In order to run tests in parallel I have created several testrunners each running in a different jvm and
each running several features and outputting (using the report plugins) to different xml and json reports.

In order to combine the reports I am intending to merge the individual xml and json reports.


问:
Subtract current row value by previous row value and get balance amount to current row
I need to get the balanceAmount by subtracting the current row value from the previous row's value. Expected result is as below.

Here is my current query

```<code>select
    pp.*,
    pp.topupAmount - sum(pp.chargeAmount) over (over by pp.ROW_NUM rows unbounded preceding) AS balanceAmount
from
    (select
         row_number() over (order by ppc.sortDate) ROW_NUM, ppc.*
     from
         (select 0 as topupAmount, t1.chargeAmount, t1.sortDate
          from t1
          union all
          select t2.topupAmount, 0 as chargeAmount, t2.sortDate
          from t2) as ppc
     ) as pp
order by
    pp.ROW_NUM
</code>```

This is what I am getting from above query

How could I achieve this?

答:
You can use window functions:

```<code>select
    t.*,
    sum(topupAmount - chargeAmount) over(order by row_num) balanceAmount
from mytable t
</code>```

Actually by looking at your query it seems like row_num is a generated column, so you likely want:

```<code>select
    t.*,
    sum(topupAmount - chargeAmount) over(order by sortDate) balanceAmount
from mytable t
</code>```

Body:
I need to get the balanceAmount by subtracting the current row value from the previous row's value. Expected result is as below.

Here is my current query

select
    pp.*,
    pp.topupAmount - sum(pp.chargeAmount) over (over by pp.ROW_NUM rows unbounded preceding) AS balanceAmount
from
    (select
         row_number() over (order by ppc.sortDate) ROW_NUM, ppc.*
     from
         (select 0 as topupAmount, t1.chargeAmount, t1.sortDate
          from t1
          union all
          select t2.topupAmount, 0 as chargeAmount, t2.sortDate
          from t2) as ppc
     ) as pp
order by
    pp.ROW_NUM

This is what I am getting from above query

How could I achieve this?

Body:
You can use window functions:

select
    t.*,
    sum(topupAmount - chargeAmount) over(order by row_num) balanceAmount
from mytable t

Actually by looking at your query it seems like row_num is a generated column, so you likely want:

select
    t.*,
    sum(topupAmount - chargeAmount) over(order by sortDate) balanceAmount
from mytable t


问:
Website nav links not working on IE9
My website: http://botvps.com

The text on the button is not appearing.
I have already made an IE css for IE 8 or lower.

What do I need to do?

Regards,
LB

答:
```<code> <!--[if IE 5]>
 <link rel="stylesheet" type="text/css" href="ie5.css" />
 <![endif]-->
 <!--[if IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6.css" />
 <![endif]-->
 <!--[if IE 7]>
 <link rel="stylesheet" type="text/css" href="ie.css" />
 <![endif]-->
 <!--[if IE 8]>
 <link rel="stylesheet" type="text/css" href="ie8.css" />
 <![endif]-->
 <link rel="stylesheet" type="text/css" href="layout.css" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: Website nav links not working on IE9


问:
Adding logger causes can't pickle _thread.RLock objects error
this is my code

class MusicHandler(object):
    """ Implements the logic to download musics """

    def __init__(self):
        """ Creates the class object, loads configs, absolute paths and create directories. Does not init download """
        # create logger
        self.logger = getLogger("music logger")
        self.logger.info("Initializing MusicHandler class object")
        # load config vars
        self.configs = utils.get_configs()
        # load absolute paths
        self.dir_music = self.configs["music_path"]
        self.dir_audio = utils.get_path_from_rel(self.configs["audio_path"], base_path=self.dir_music)
        self.dir_video = utils.get_path_from_rel(self.configs["video_path"], base_path=self.dir_music)
        self.taboo_path = utils.get_path_from_rel(self.configs["taboo_path"])
        # make dir if not exists
        list(map(utils.make_dir_safe, (self.dir_music, self.dir_audio, self.dir_video)))

    @run_safe
    def download_one(self, link, keep_video=False):
        """ handles the download of one link. keep_video determines if video is saved or deleted. """
        self.logger.info(f"Starting download of {link}")
        if self.is_taboo(link):
            self.logger.warning("Link is taboo, will skip it.")
            return
        name = self.download_video(link)
        self.logger.info(f"Download of {name} (video) was a success.")
        self.video_to_audio(name)
        self.add_to_taboo(link)
        if not keep_video:
            self.remove_video(name)
        self.logger.critical(f"Successfully downloaded {name}. Available at {self.dir_music}.")

    def get_musics_linear(self, url_list):
        """ Linear download of all links from list """
        for link in url_list:
            self.download_one(link)

    @run_safe
    def get_musics_parallel(self, url_list, num_procs=3):
        """ Parallel download of  all links from list """
        with Pool(num_procs) as p:
            print("here")
            p.map(self.download_one, url_list)
            print("there")

    def is_taboo(self, link):
        """ Verifies if link exists in the taboo file """
        return utils.is_in_file(self.taboo_path, link)

    def add_to_taboo(self, link):
        """ Adds link to the taboo file """
        utils.append_to_file(self.taboo_path, link)

    def download_video(self, link):
        """ Downloads the highest resolution video given a link. Returns file name """
        yt = YouTube(link)
        yt.streams.filter(progressive=True).order_by("resolution").desc().first().download(self.dir_video, yt.title)
        return utils.safe_filename(yt.title)

    def download_audio(self, link):
        """ Downloads only the audio of a given link. Returns file name """
        yt = YouTube(link)
        yt.streams.filter(only_audio=True).first().download(self.dir_audio, yt.title)
        return utils.safe_filename(yt.title)

    def video_to_audio(self, name):
        """ Converts a video to an audio file """
        self.logger.info("Converting video to audio.")
        video_f_path = os.path.join(self.dir_video, "{}{}".format(name, ".mp4"))
        audio_f_path = os.path.join(self.dir_audio, "{}{}".format(name, ".wav"))
        cmd_list = ["ffmpeg", "-i", video_f_path, "-f", "wav", "-ab", "19200", "-vn", audio_f_path]
        FNULL = open(os.devnull, 'w')
        subprocess.call(cmd_list, stdout=FNULL, stderr=subprocess.STDOUT)

    def remove_video(self, name):
        """ Deletes a video file """
        self.logger.info("Removing video file.")
        video_f_path = os.path.join(self.dir_video, "{}{}".format(name, ".mp4"))
        if os.path.exists(video_f_path):
            os.remove(video_f_path)```

when running this code, I get the following error:

File "C:\Users\Y\PycharmProjects\pyMusic\lib\pyMusic.py", line 143, in get_musics_parallel
      p.map(self.download_one, url_list)
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\pool.py", line 266, in map
      return self._map_async(func, iterable, mapstar, chunksize).get()
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\pool.py", line 644, in get
      raise self._value
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\pool.py", line 424, in _handle_tasks
      put(task)
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\connection.py", line 206, in send
      self._send_bytes(_ForkingPickler.dumps(obj))
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\reduction.py", line 51, in dumps
      cls(buf, protocol).dump(obj)
  TypeError: can't pickle _thread.RLock objects

However, if I remove the logger, the code executes without any problem.

Any idea about why the logger is causing this pickle error?
The error is on the "get_musics_parallel" function, and occurs on the map(self.download_one, urllist) line.

I tried to google this error, but the questions relative to this pickle error seem not the be related to my problem.

I appreciate your help,
Kind regards

答:
I find the same error, but the same code, on a different machine, raises no error.

The difference is: the machine where the code is not working is using python3.6.7
The machine where the same code is working is using python3.7.6

So my answer is: if possible, upgrade to python 3.7.6

Not sure why it works though.

Body:
this is my code

class MusicHandler(object):
    """ Implements the logic to download musics """

    def __init__(self):
        """ Creates the class object, loads configs, absolute paths and create directories. Does not init download """
        # create logger
        self.logger = getLogger("music logger")
        self.logger.info("Initializing MusicHandler class object")
        # load config vars
        self.configs = utils.get_configs()
        # load absolute paths
        self.dir_music = self.configs["music_path"]
        self.dir_audio = utils.get_path_from_rel(self.configs["audio_path"], base_path=self.dir_music)
        self.dir_video = utils.get_path_from_rel(self.configs["video_path"], base_path=self.dir_music)
        self.taboo_path = utils.get_path_from_rel(self.configs["taboo_path"])
        # make dir if not exists
        list(map(utils.make_dir_safe, (self.dir_music, self.dir_audio, self.dir_video)))

    @run_safe
    def download_one(self, link, keep_video=False):
        """ handles the download of one link. keep_video determines if video is saved or deleted. """
        self.logger.info(f"Starting download of {link}")
        if self.is_taboo(link):
            self.logger.warning("Link is taboo, will skip it.")
            return
        name = self.download_video(link)
        self.logger.info(f"Download of {name} (video) was a success.")
        self.video_to_audio(name)
        self.add_to_taboo(link)
        if not keep_video:
            self.remove_video(name)
        self.logger.critical(f"Successfully downloaded {name}. Available at {self.dir_music}.")

    def get_musics_linear(self, url_list):
        """ Linear download of all links from list """
        for link in url_list:
            self.download_one(link)

    @run_safe
    def get_musics_parallel(self, url_list, num_procs=3):
        """ Parallel download of  all links from list """
        with Pool(num_procs) as p:
            print("here")
            p.map(self.download_one, url_list)
            print("there")

    def is_taboo(self, link):
        """ Verifies if link exists in the taboo file """
        return utils.is_in_file(self.taboo_path, link)

    def add_to_taboo(self, link):
        """ Adds link to the taboo file """
        utils.append_to_file(self.taboo_path, link)

    def download_video(self, link):
        """ Downloads the highest resolution video given a link. Returns file name """
        yt = YouTube(link)
        yt.streams.filter(progressive=True).order_by("resolution").desc().first().download(self.dir_video, yt.title)
        return utils.safe_filename(yt.title)

    def download_audio(self, link):
        """ Downloads only the audio of a given link. Returns file name """
        yt = YouTube(link)
        yt.streams.filter(only_audio=True).first().download(self.dir_audio, yt.title)
        return utils.safe_filename(yt.title)

    def video_to_audio(self, name):
        """ Converts a video to an audio file """
        self.logger.info("Converting video to audio.")
        video_f_path = os.path.join(self.dir_video, "{}{}".format(name, ".mp4"))
        audio_f_path = os.path.join(self.dir_audio, "{}{}".format(name, ".wav"))
        cmd_list = ["ffmpeg", "-i", video_f_path, "-f", "wav", "-ab", "19200", "-vn", audio_f_path]
        FNULL = open(os.devnull, 'w')
        subprocess.call(cmd_list, stdout=FNULL, stderr=subprocess.STDOUT)

    def remove_video(self, name):
        """ Deletes a video file """
        self.logger.info("Removing video file.")
        video_f_path = os.path.join(self.dir_video, "{}{}".format(name, ".mp4"))
        if os.path.exists(video_f_path):
            os.remove(video_f_path)

when running this code, I get the following error:

File "C:\Users\Y\PycharmProjects\pyMusic\lib\pyMusic.py", line 143, in get_musics_parallel
      p.map(self.download_one, url_list)
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\pool.py", line 266, in map
      return self._map_async(func, iterable, mapstar, chunksize).get()
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\pool.py", line 644, in get
      raise self._value
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\pool.py", line 424, in _handle_tasks
      put(task)
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\connection.py", line 206, in send
      self._send_bytes(_ForkingPickler.dumps(obj))
    File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\multiprocessing\reduction.py", line 51, in dumps
      cls(buf, protocol).dump(obj)
  TypeError: can't pickle _thread.RLock objects

However, if I remove the logger, the code executes without any problem.

Any idea about why the logger is causing this pickle error?
The error is on the "get_musics_parallel" function, and occurs on the map(self.download_one, urllist) line.

I tried to google this error, but the questions relative to this pickle error seem not the be related to my problem.

I appreciate your help,
Kind regards


问:
unexpected results when converting nvarchar to datetime using substrings
I have to deal with the following columns:

```<code>StartTime (nvarchar(10), null)
StartDate (nvarchar(10), null)
</code>```

StartTime contains the Time as following: hhmmss

StartDate contains the Date as following: yyyymmdd (m=month)

To concatenate and convert StartDate and StartTime to a datetime i use the following code inside a stored procedure:

```<code>TRY_CAST(SUBSTRING(xy.StartDate,7,2) + '.' + SUBSTRING(xy.StartDate,5,2) + '.' + SUBSTRING(xy.StartDate,1,4) + ' ' + SUBSTRING(xy.StartTime,1,2) + ':' + SUBSTRING(xy.StartTime,3,2) + ':' + SUBSTRING(xy.StartTime,5,2) as datetime) as FULLSTARTDATE
</code>```

Now imagine these values for two cases:

Case 1:

```<code>StartTime = 000000
StartDate = 20191201
FULLSTARTDATE = 2019-01-12 00:00:00.000
</code>```

Case 2:

```<code>StartTime = 000000
StartDate = 20191220
FULLSTARTDATE = NULL
</code>```

Why does Case 2 not output 2019-20-12? It may be a trivial issue but i can't seem to figure it out for almost an hour now.

答:
It seems to me, that you are composing a date/time string in the form "DD.MM.YYYY HH:MM:SS", which seems to get interpreted as "MM.DD.YYYY HH:MM:SS" instead.

I see two possible solutions (but there might be more):

1: use "YYYY.MM.DD HH:MM:SS", which cannot be interpreted "incorrectly":

```<code>TRY_CAST(
    SUBSTRING(xy.StartDate,1,4) + '.' +
    SUBSTRING(xy.StartDate,5,2) + '.' +
    SUBSTRING(xy.StartDate,7,2) + ' ' +
    SUBSTRING(xy.StartTime,1,2) + ':' +
    SUBSTRING(xy.StartTime,3,2) + ':' +
    SUBSTRING(xy.StartTime,5,2) as datetime) as FULLSTARTDATE
</code>```

2: use CONVERT instead of TRY_CAST:

```<code>CONVERT(DATETIME, xy.StartDate, 104) +
CONVERT(DATETIME,
  SUBSTRING(xy.StartTime,1,2) + ':' +
  SUBSTRING(xy.StartTime,3,2) + ':' +
  SUBSTRING(xy.StartTime,5,2), 108) as FULLSTARTDATE
</code>```

Body:
I have to deal with the following columns:

StartTime (nvarchar(10), null)
StartDate (nvarchar(10), null)

StartTime contains the Time as following: hhmmss

StartDate contains the Date as following: yyyymmdd (m=month)

To concatenate and convert StartDate and StartTime to a datetime i use the following code inside a stored procedure:

TRY_CAST(SUBSTRING(xy.StartDate,7,2) + '.' + SUBSTRING(xy.StartDate,5,2) + '.' + SUBSTRING(xy.StartDate,1,4) + ' ' + SUBSTRING(xy.StartTime,1,2) + ':' + SUBSTRING(xy.StartTime,3,2) + ':' + SUBSTRING(xy.StartTime,5,2) as datetime) as FULLSTARTDATE

Now imagine these values for two cases:

Case 1:

StartTime = 000000
StartDate = 20191201
FULLSTARTDATE = 2019-01-12 00:00:00.000

Case 2:

StartTime = 000000
StartDate = 20191220
FULLSTARTDATE = NULL

Why does Case 2 not output 2019-20-12? It may be a trivial issue but i can't seem to figure it out for almost an hour now.

Body:
It seems to me, that you are composing a date/time string in the form "DD.MM.YYYY HH:MM:SS", which seems to get interpreted as "MM.DD.YYYY HH:MM:SS" instead.

I see two possible solutions (but there might be more):

1: use "YYYY.MM.DD HH:MM:SS", which cannot be interpreted "incorrectly":

TRY_CAST(
    SUBSTRING(xy.StartDate,1,4) + '.' +
    SUBSTRING(xy.StartDate,5,2) + '.' +
    SUBSTRING(xy.StartDate,7,2) + ' ' +
    SUBSTRING(xy.StartTime,1,2) + ':' +
    SUBSTRING(xy.StartTime,3,2) + ':' +
    SUBSTRING(xy.StartTime,5,2) as datetime) as FULLSTARTDATE

2: use CONVERT instead of TRY_CAST:

CONVERT(DATETIME, xy.StartDate, 104) +
CONVERT(DATETIME,
  SUBSTRING(xy.StartTime,1,2) + ':' +
  SUBSTRING(xy.StartTime,3,2) + ':' +
  SUBSTRING(xy.StartTime,5,2), 108) as FULLSTARTDATE


问:
read specific single element value from xml using vb
I am trying to read specific element value from below xml:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document Version="7.700000" VersionSeemage="7.7.0.101">
<Server Type="CLitServerModifiable">
    <CLitInfo>
        <Neutral>
            <GroupInfoPropSet>
                <GroupInfo.List/>
                <GroupInfo.Guid Value="a126be064a25ce3f"/>
            </GroupInfoPropSet>
        </Neutral>
    </CLitInfo>
</Server>
</Document>
</code>```

I need only this string a126be064a25ce3f. As I am very new to this. I tried below code:

```<code>Dim doc As XmlDocument = New XmlDocument()
doc.Load("test.xml")
Dim str As String = doc.SelectSingleNode("DocumentSmg/Server[Type='CLitServerModifiable']/CLitBOMInfo/Neutral/GroupInfoPropSet/GroupInfo.List/GroupInfo.Guid").InnerText
 MsgBox(str)
</code>```

It returns nothing

答:
Try xml linq :</p>

```<code>Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)
        Dim guid As String = CType(doc.Descendants("GroupInfo.Guid").FirstOrDefault().Attribute("Value"), String)

    End Sub
End Module
</code>```

Body:
I am trying to read specific element value from below xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document Version="7.700000" VersionSeemage="7.7.0.101">
<Server Type="CLitServerModifiable">
    <CLitInfo>
        <Neutral>
            <GroupInfoPropSet>
                <GroupInfo.List/>
                <GroupInfo.Guid Value="a126be064a25ce3f"/>
            </GroupInfoPropSet>
        </Neutral>
    </CLitInfo>
</Server>
</Document>

I need only this string a126be064a25ce3f. As I am very new to this. I tried below code:

Dim doc As XmlDocument = New XmlDocument()
doc.Load("test.xml")
Dim str As String = doc.SelectSingleNode("DocumentSmg/Server[Type='CLitServerModifiable']/CLitBOMInfo/Neutral/GroupInfoPropSet/GroupInfo.List/GroupInfo.Guid").InnerText
 MsgBox(str)

It returns nothing

Body:
Try xml linq :

Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)
        Dim guid As String = CType(doc.Descendants("GroupInfo.Guid").FirstOrDefault().Attribute("Value"), String)

    End Sub
End Module


问:
Oracle Apex 19.x external URL based on items value
I'm using Application Express 19.2.0.00.18 with Oracle Database 12c Enterprise Edition Release 12.2.0.1.0.
In our applications (from 4.x) we use Jaspersoft Reports to create PDFs (invoices, labels, shipping documents, etc.) and we use a db function that take in parameters like report name and page items values and returns an html tag for link.
E.G.:

```<code>myFunction (myReportName, P01_ITEM_A ,P01_ITEM_B)
return
<a href="http://myjasperserver/rest/myReportName.pdf?x=itemAvalue&y=itemBvalue"><img scr="/imagespath/pdf.png"></a>
</code>```

In this way it is possible to render where needed a clickable image to generate a report based on actual values of items. This solution is heavy adopted in our Apex applications but we are facing some difficulties trying to do the same in 19.x.
We need some help or suggestions in order to reproduce the same feature or to do the same in a different way.

As suggested by Littlefoot I can specify that "difficulties" are :

In Apex 4.x the query : select someFieldList ,myFunction (myReportName, P01_ITEM_A ,P01_ITEM_B) PDF from dual results in a report with the column PDF that is a clickable image (or text, the png is not mandatory). In Apex 19.x the same query results in a report with the column PDF rendered as Plain Text.

In Apex 4.x if I use the same query as Source attribute of a Display Only item it is rendered as a clickable link (text or image). In Apex 19.x the Display Only item is always not clickable.

答:
The solution to both issues is the same.  APEX 19.2 is a lot more advanced than APEX 4.x, and by default is more secure.  For both Plain Text report columns and Display Only page items the default security setting is "Escape special characters":

This deliberately escapes any HTML tags in the contents to avoid potential XSS (cross-site scripting) security risks.

Simply unselect this setting and your links will appear as links again.

Body:
I'm using Application Express 19.2.0.00.18 with Oracle Database 12c Enterprise Edition Release 12.2.0.1.0.
In our applications (from 4.x) we use Jaspersoft Reports to create PDFs (invoices, labels, shipping documents, etc.) and we use a db function that take in parameters like report name and page items values and returns an html tag for link.
E.G.:

myFunction (myReportName, P01_ITEM_A ,P01_ITEM_B)
return

In this way it is possible to render where needed a clickable image to generate a report based on actual values of items. This solution is heavy adopted in our Apex applications but we are facing some difficulties trying to do the same in 19.x.
We need some help or suggestions in order to reproduce the same feature or to do the same in a different way.

As suggested by Littlefoot I can specify that "difficulties" are :

In Apex 4.x the query : select someFieldList ,myFunction (myReportName, P01_ITEM_A ,P01_ITEM_B) PDF from dual results in a report with the column PDF that is a clickable image (or text, the png is not mandatory). In Apex 19.x the same query results in a report with the column PDF rendered as Plain Text.

In Apex 4.x if I use the same query as Source attribute of a Display Only item it is rendered as a clickable link (text or image). In Apex 19.x the Display Only item is always not clickable.


问:
How to correctly set up multiple product offer schema per page
For some reason I am having great difficulty finding this out. I have had a look here:

https://developers.google.com/search/docs/data-types/product

And here:

https://schema.org/Product

But none of the examples given show me how to add multiple product offers on a page. To illustrate what I am talking about, here is an example on our site:

https://reclaimdesign.org/vases-reclaimed-wood-stands.html

I have been having a to and fro with RankMath support about this and they tell me this is not possible. I don't believe they are right in saying that but I cannot find 100% irrefutable evidence to illustrate otherwise.

I am currently working to set up the schema myself (as the to and fro is now feeling like a waste of time). My schema code for the above page validates in the Structured Data Testing Tool:

```<code>`<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Product",
  "brand": "Reclaim Design",
  "logo": "https://reclaimdesign.org/wp-content/uploads/reclaim-design-logo.jpg",
  "name": "4 Glamorous Sustainable Vases – Home Decor | Reclaim Design",
  "image": [   "https://reclaimdesign.org/wp-content/uploads/1x1/test-tube-vases-sustainable-reclaimed-wood-stand1.jpg",
"https://reclaimdesign.org/wp-content/uploads/4x3/test-tube-vases-sustainable-reclaimed-wood-stand1.jpg",
"https://reclaimdesign.org/wp-content/uploads/16x9/test-tube-vases-sustainable-reclaimed-wood-stand1.jpg","https://reclaimdesign.org/wp-content/uploads/1x1/test-tube-vases-sustainable-reclaimed-wood-stand5.jpg",
"https://reclaimdesign.org/wp-content/uploads/4x3/test-tube-vases-sustainable-reclaimed-wood-stand5.jpg",
"https://reclaimdesign.org/wp-content/uploads/16x9/test-tube-vases-sustainable-reclaimed-wood-stand5.jpg","https://reclaimdesign.org/wp-content/uploads/1x1/bottle-vases-sustainable-reclaimed-wood-stand1.jpg",
"https://reclaimdesign.org/wp-content/uploads/4x3/bottle-vases-sustainable-reclaimed-wood-stand1.jpg",
"https://reclaimdesign.org/wp-content/uploads/16x9/bottle-vases-sustainable-reclaimed-wood-stand1.jpg","https://reclaimdesign.org/wp-content/uploads/1x1/recycled-gin-bottle-vase-sustainable-reclaimed-wood-stand.jpg",
"https://reclaimdesign.org/wp-content/uploads/4x3/recycled-gin-bottle-vase-sustainable-reclaimed-wood-stand.jpg",
"https://reclaimdesign.org/wp-content/uploads/16x9/recycled-gin-bottle-vase-sustainable-reclaimed-wood-stand.jpg"
   ],
  "url": "https://reclaimdesign.org/vases-reclaimed-wood-stands.html",
  "@id": "https://reclaimdesign.org/vases-reclaimed-wood-stands.html",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "https://reclaimdesign.org/search?q={search_term_string}",
    "query-input": "required name=search_term_string"
  },
  "sameAs":
["https://www.facebook.com/reclaimdesignza",
"https://twitter.com/ReclaimDesignZA",
"https://www.instagram.com/reclaimdesign/",
"https://za.pinterest.com/reclaimdesignza/",
"https://www.google.com/maps/place/Reclaim+Design/@-34.03081,18.4517513,17z/data=!3m1!4b1!4m5!3m4!1s0x1dcc4242e6ad5367:0xcf5844aec51f1a43!8m2!3d-34.03081!4d18.45394"
],
  "description": "Click here to find out more about our sustainable vases and vase sets with reclaimed wood stands | Reclaim Design",
  "offers": [{
    "@type": "Offer",
    "availability": "http://schema.org/InStock",
    "price": "390",
    "priceCurrency": "ZAR",
    "url": "https://reclaimdesign.org/home-decor-shop.html/Test-Tube-Vases-With-Stand-p134947241"
  },{
    "@type": "Offer",
    "availability": "http://schema.org/InStock",
    "price": "290",
    "priceCurrency": "ZAR",
    "url": "https://reclaimdesign.org/home-decor-shop.html/Test-Tube-Vases-With-Stand-p134947241"
  },{
    "@type": "Offer",
    "availability": "http://schema.org/InStock",
    "price": "370",
    "priceCurrency": "ZAR",
    "url": "https://reclaimdesign.org/home-decor-shop.html/Bottle-Vases-with-Stand-p65343612"
  },{
    "@type": "Offer",
    "availability": "http://schema.org/InStock",
    "price": "250",
    "priceCurrency": "ZAR",
    "url": "https://reclaimdesign.org/vases-reclaimed-wood-stands.html"
  },{
    "@type": "Offer",
    "availability": "http://schema.org/InStock",
    "price": "300",
    "priceCurrency": "ZAR",
    "url": "https://reclaimdesign.org/home-decor-shop.html/Floating-Globe-Vase-With-Stand-p65346003"
  }]
}
</script>`
</code>```

The RankMath support tell me "you should not use more than one product Schema per page. It does not make much sense and would only confuse Google." If they are right, why then would the code validate in Google's own testing tool?

Please can somebody with experience in this arena explain which is the correct way of doing this? TIA

答:
You can markup your services as a product.

Two reasons to do this

Google doesn’t support “service” markup
Services are included in Product’s definition in schema.org
If you have multiple different services on a single page, then markup them one by one - individually.

If you have same services but with vivid options and price packages then use aggregate product markup.

Read about Google’s structured data product markup. You will get the sample code, which you can modify as per the requirements.

Body:
For some reason I am having great difficulty finding this out. I have had a look here:

https://developers.google.com/search/docs/data-types/product

And here:

https://schema.org/Product

But none of the examples given show me how to add multiple product offers on a page. To illustrate what I am talking about, here is an example on our site:

https://reclaimdesign.org/vases-reclaimed-wood-stands.html

I have been having a to and fro with RankMath support about this and they tell me this is not possible. I don't believe they are right in saying that but I cannot find 100% irrefutable evidence to illustrate otherwise.

I am currently working to set up the schema myself (as the to and fro is now feeling like a waste of time). My schema code for the above page validates in the Structured Data Testing Tool:

``

The RankMath support tell me "you should not use more than one product Schema per page. It does not make much sense and would only confuse Google." If they are right, why then would the code validate in Google's own testing tool?

Please can somebody with experience in this arena explain which is the correct way of doing this? TIA


答:
You need window function :</p>

```<code>select t.*, sum(topupAmount - chargeAmount) over (order by sortDate) as balanceAmount
from table t;
</code>```

Title: Subtract current row value by previous row value and get balance amount to current row

Body:
You need window function :

select t.*, sum(topupAmount - chargeAmount) over (order by sortDate) as balanceAmount
from table t;


问:
Is it okay to do another process inside the filter method in java 8 streams
I know how to filter a collection based on condition and collect. I am wondering is it okay to do another process inside the filter.

```<code>List<SupplementaryCustomer> supplementaryCustomersWithMoreThan100Points = new ArrayList<>();
List<Customer> customersWithMoreThan100Points = customers
  .stream()
  .filter(c -> {
     boolean isOkay = c.getPoints() > 100;
     if(isOkay && (c.isSupplementaryCustomer())){
       SupplementaryCustomer.add(c);
     }
     return isOkay;
   })
  .collect(Collectors.toList());

</code>```

let's say that customers object has all types of customers. and i needed to get supplementary customers With MoreThan 100 Points and customers With More Than 100 Points. i am doing something like this in my codebase. is it okay to do something like this?

答:
Streams should be side effect free except for terminal operations that are intended for side-effects (foreach). What you're doing is violating this paradigm. The cost of streaming the resulting list again and then filtering by your other critera for adding to the other list is neglible if there aren't millions of items in your list and even then I'd advocate against violating languager paradigms to gain a small performance boost.

```<code>List<Customer> customersWithMoreThan100Points = customers
  .stream()
  .filter(c -> c.getPoints() > 100)
  .collect(Collectors.toList());

List<SupplementaryCustomer> supplementaryCustomersWithMoreThan100Points = customersWithMoreThan100Points
    .stream()
    .filter(c -> c.isSupplementaryCustomer())
    .collect(Collectors.toList());
</code>```

It's easier to read, less complex, more compliant to the intent of Streams and I doubt you'll find a noticeable (or even measurable) perfomance loss in any typical use case.

Body:
I know how to filter a collection based on condition and collect. I am wondering is it okay to do another process inside the filter.

List<SupplementaryCustomer> supplementaryCustomersWithMoreThan100Points = new ArrayList<>();
List<Customer> customersWithMoreThan100Points = customers
  .stream()
  .filter(c -> {
     boolean isOkay = c.getPoints() > 100;
     if(isOkay && (c.isSupplementaryCustomer())){
       SupplementaryCustomer.add(c);
     }
     return isOkay;
   })
  .collect(Collectors.toList());

let's say that customers object has all types of customers. and i needed to get supplementary customers With MoreThan 100 Points and customers With More Than 100 Points. i am doing something like this in my codebase. is it okay to do something like this?

Body:
Streams should be side effect free except for terminal operations that are intended for side-effects (foreach). What you're doing is violating this paradigm. The cost of streaming the resulting list again and then filtering by your other critera for adding to the other list is neglible if there aren't millions of items in your list and even then I'd advocate against violating languager paradigms to gain a small performance boost.

List<Customer> customersWithMoreThan100Points = customers
  .stream()
  .filter(c -> c.getPoints() > 100)
  .collect(Collectors.toList());

List<SupplementaryCustomer> supplementaryCustomersWithMoreThan100Points = customersWithMoreThan100Points
    .stream()
    .filter(c -> c.isSupplementaryCustomer())
    .collect(Collectors.toList());

It's easier to read, less complex, more compliant to the intent of Streams and I doubt you'll find a noticeable (or even measurable) perfomance loss in any typical use case.


问:
default model binder
Basically i have a form with around 100 elements. The values bind to my model when i submit the form. But i want to work on certain values of the form elements before the values are set. Basically i want the 95 values of elements of the form be set by the default binder but i want to work on the values of five elements before it is set.

Any suggestions as to how to go about doing it by overriding the default model binder ?

答: I could achieve the same by overriding the BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor) function in the DefaultBinder</p>

Title: default model binder


问:
How to create a PHP dropdown list that allows you to select multiple options?
This is the basis for the code I'm using, drawing options from a database but no matter how I alter this code I will only let me select 1 option or return an error.</p>

```<code><select name="sargentid" id="fieldsargentid" class="form-control">

<?php foreach ($sargent as $sargent) { echo "<option value='" . $sargent->getID() .
"'>$sargent</option>"; }?>

</select>
</code>```

答:
```<code><select name="sargentid" id="fieldsargentid" class="form-control" multiple>
<? foreach($argent as $data){?>
<option value="<?=$data->getID() ?>"><?= $data ?></option>
<?php } ?>
</select>
</code>```

Try This

Body:
This is the basis for the code I'm using, drawing options from a database but no matter how I alter this code I will only let me select 1 option or return an error.

<select name="sargentid" id="fieldsargentid" class="form-control">

<?php foreach ($sargent as $sargent) { echo "<option value='" . $sargent->getID() .
"'>$sargent</option>"; }?>

</select>

Body:
<select name="sargentid" id="fieldsargentid" class="form-control" multiple>
<? foreach($argent as $data){?>
<option value="<?=$data->getID() ?>"><?= $data ?></option>
<?php } ?>
</select>

Try This


问:
What's the Nodejs backend routine for "Register / Signin with Google"?
I'm using a Express Nodejs backend + React frontend set up and tried to implement a "Register / Signin with Google" function, but I do not understand what to store in the database after the user is authenticated. In the ordinary register with email approach, I send the email + password to the backend when I register and check if both the email & password match when the user login.

However, I don't know what to store in the db if one is registered with Google. I have already implement part of the google auth with google by following this tutorial in the frontend side, here's my code:

```<code>import * as queryString from 'query-string';

const stringifiedParams = queryString.stringify({
  client_id: 'MY_CLIENT_ID'
  redirect_uri: 'http://localhost:8000/protected_home',
  scope: [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
  ].join(' '), // space seperated string
  response_type: 'code',
  access_type: 'offline',
  prompt: 'consent'
});

const googleLoginUrl = `https://accounts.google.com/o/oauth2/v2/auth?${stringifiedParams}`;

return (
  <a href={googleLoginUrl}>Login with Google</a>
)
</code>```

But then what's next? I've successfully pass through the auth process and redirected back to the protected_home page. But this only means that this user is a google user, what kind of information should I store their information in backend so that it indicated that the user has registered an account in my backend with this google account?

Also, is is possible to move the logic above to backend? Since google will redirect back to my redirect_urilike this http://localhost:8000/protected_home?code=CODE_IS_HERE, I need to browser to extract the information in CODE_IS_HERE. So it seems impossible to move the login logic to backend, any solution?

答:
Basically you should not write it from scratch as there are libraries that deal with Oauth2: PassportJS, openid-client, Grant, OAuth2-client-js. Those should handle all the below steps except storing actual details in your own database.

In general there are some basic steps when implementing third party oauth2 authentication:

Understand well how Oauth2 works https://www.rfc-editor.org/rfc/rfc6749

Redirect to your server from client (react)

Request authorization by redirecting to Google

Get authorization code which will be added to a url in a redirect from google back to your server

Exchange code for an access token (POST)

Use access token to get user profile details from Google (POST)

Save user details if they do not exist yet in your database - in theory you could skip this part

Create session/token and send it back to client (React) - it is another redirect.

You could also not store any user details on your server and just pass back the token obtained from Google to your React app (client), but then you'd need to check if it is valid on every request to your server. Which is why it is simpler to create your own session token and send it to the client.

There are more details as this is quite a topic to start with but RFC6749 should fill in the gaps.

Body:
I'm using a Express Nodejs backend + React frontend set up and tried to implement a "Register / Signin with Google" function, but I do not understand what to store in the database after the user is authenticated. In the ordinary register with email approach, I send the email + password to the backend when I register and check if both the email & password match when the user login.

However, I don't know what to store in the db if one is registered with Google. I have already implement part of the google auth with google by following this tutorial in the frontend side, here's my code:

import * as queryString from 'query-string';

const stringifiedParams = queryString.stringify({
  client_id: 'MY_CLIENT_ID'
  redirect_uri: 'http://localhost:8000/protected_home',
  scope: [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
  ].join(' '), // space seperated string
  response_type: 'code',
  access_type: 'offline',
  prompt: 'consent'
});

const googleLoginUrl = `https://accounts.google.com/o/oauth2/v2/auth?${stringifiedParams}`;

return (
  Login with Google
)

But then what's next? I've successfully pass through the auth process and redirected back to the protected_home page. But this only means that this user is a google user, what kind of information should I store their information in backend so that it indicated that the user has registered an account in my backend with this google account?

Also, is is possible to move the logic above to backend? Since google will redirect back to my redirect_urilike this http://localhost:8000/protected_home?code=CODE_IS_HERE, I need to browser to extract the information in CODE_IS_HERE. So it seems impossible to move the login logic to backend, any solution?


问:
Images in ViewPager don't fill the screen
I am receiving a set of URL images from API to show as slider so I am using viewpager to do my job and when I am trying to set Images in viewpager to fill screen according to imagesize this doesn't happen at all.

All the red line is huge spacing.. I am not sure why this there?

I am trying do the following in XML:

```<code><RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/noData"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="@string/nointernet"
                android:textColor="#000000"
                android:textSize="14sp"
                android:textStyle="italic"
                android:visibility="gone" />

            <android.support.v4.view.ViewPager
                android:id="@+id/myviewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </android.support.v4.view.ViewPager>

            <FrameLayout
                android:id="@+id/progressContainer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:visibility="gone"
                android:layout_centerVertical="true">

                <com.ylg.librarys.ProgressWheel xmlns:wheel="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/progress_wheel"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:visibility="visible"
                    app:matProg_barColor="@color/colorPrimary"
                    app:matProg_progressIndeterminate="true" />
            </FrameLayout>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/pagerLayoutIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pagerIndicator"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="2dp">

            <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:fillColor="@color/orangeText"
                app:pageColor="@color/whitetext"
                app:strokeColor="@color/orangeText" />
        </RelativeLayout>
</code>```

PageAdapter looks like this:

```<code>@Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            progressContainer.setVisibility(View.GONE);

            wheel_layout.setVisibility(View.GONE);

            noData = (TextView)rootView.findViewById(R.id.noData);
            noData.setVisibility(View.GONE);

            ImageView imageView = new ImageView(getActivity());
            imageLoader.DisplayImage(bannerItems.get(position).getbannerImage(), 0, imageView);

            LayoutParams imageParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            imageView.setLayoutParams(imageParams);

            LinearLayout layout = new LinearLayout(getActivity());
            layout.setOrientation(LinearLayout.VERTICAL);
            LayoutParams layoutParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            layout.setLayoutParams(layoutParams);
            layout.addView(imageView);

            final int page = position;
            layout.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(),
                            "Page " + page + " clicked",
                            Toast.LENGTH_LONG).show();
                }});

            container.addView(layout);

            return layout;
        }
</code>```

Strangely If I don't give the height for the relativeLayout in which viewpager is sitting I don't see the image at all. that is If I set:

```<code>       <RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">
</code>```

I only get PageIndicator. Above ViewPager with image is not shown at all.

Not sure why this happening? How do I set the image match_parent so that it shows full without any gap?

答:
Add this in your instantiateItem method

imageView.setScaleType(ImageView.ScaleType.FIT_XY);

This will fill the whole screen with image removing whitespaces.

You can also try other methods

```<code>imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
</code>```

Body:
I am receiving a set of URL images from API to show as slider so I am using viewpager to do my job and when I am trying to set Images in viewpager to fill screen according to imagesize this doesn't happen at all.

All the red line is huge spacing.. I am not sure why this there?

I am trying do the following in XML:

<RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/noData"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="@string/nointernet"
                android:textColor="#000000"
                android:textSize="14sp"
                android:textStyle="italic"
                android:visibility="gone" />

            <android.support.v4.view.ViewPager
                android:id="@+id/myviewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </android.support.v4.view.ViewPager>

            <FrameLayout
                android:id="@+id/progressContainer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:visibility="gone"
                android:layout_centerVertical="true">

                <com.ylg.librarys.ProgressWheel xmlns:wheel="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/progress_wheel"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_gravity="center"
                    android:visibility="visible"
                    app:matProg_barColor="@color/colorPrimary"
                    app:matProg_progressIndeterminate="true" />
            </FrameLayout>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/pagerLayoutIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pagerIndicator"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="2dp">

            <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:fillColor="@color/orangeText"
                app:pageColor="@color/whitetext"
                app:strokeColor="@color/orangeText" />
        </RelativeLayout>

PageAdapter looks like this:

@Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            progressContainer.setVisibility(View.GONE);

            wheel_layout.setVisibility(View.GONE);

            noData = (TextView)rootView.findViewById(R.id.noData);
            noData.setVisibility(View.GONE);

            ImageView imageView = new ImageView(getActivity());
            imageLoader.DisplayImage(bannerItems.get(position).getbannerImage(), 0, imageView);

            LayoutParams imageParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            imageView.setLayoutParams(imageParams);

            LinearLayout layout = new LinearLayout(getActivity());
            layout.setOrientation(LinearLayout.VERTICAL);
            LayoutParams layoutParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            layout.setLayoutParams(layoutParams);
            layout.addView(imageView);

            final int page = position;
            layout.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(),
                            "Page " + page + " clicked",
                            Toast.LENGTH_LONG).show();
                }});

            container.addView(layout);

            return layout;
        }

Strangely If I don't give the height for the relativeLayout in which viewpager is sitting I don't see the image at all. that is If I set:

       <RelativeLayout
            android:id="@+id/pagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/searchlayout"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="2dp"
            android:orientation="vertical">

I only get PageIndicator. Above ViewPager with image is not shown at all.

Not sure why this happening? How do I set the image match_parent so that it shows full without any gap?

Body:
Add this in your instantiateItem method

imageView.setScaleType(ImageView.ScaleType.FIT_XY);

This will fill the whole screen with image removing whitespaces.

You can also try other methods

imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);


问:
Python write both commands and their output to a file
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')
</code>```

Now if I want to capture its output only I know I can just do:

```<code>python3 outtest.py > outtest.txt
</code>```

However, this will only give me an outtest.txt file with e.g.:

```<code>mean: 0.34
median: 0.27
</code>```

What I'm looking for is a way to get an output file like:

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27
</code>```

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

答:
You can call the script and inspect its output. You'll have to make some assumptions though. The output is only from stdout, only from lines containing the string "print", and each print produces only one line of output. That being the case, an example command to run it:

```<code>> python writer.py script.py
</code>```

And the script would look like this:

```<code>from sys import argv
from subprocess import run, PIPE

script = argv[1]
r = run('python ' + script, stdout=PIPE)
out = r.stdout.decode().split('\n')

with open(script, 'r') as f:
    lines = f.readlines()

with open('out.txt', 'w') as f:
    i = 0
    for line in lines:
        f.write(line)
        if 'print' in line:
            f.write('>>> ' + out[i])
            i += 1
</code>```

And the output:

```<code>import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>>> mean: 0.33
d_median = round(median(d), 2)
print(f'median: {d_median}')
>>> median: 0.24
</code>```

More complex cases with multiline output or other statements producing output, this won't work. I guess it would require some in depth introspection.

Body:
Is there any way to write both commands and their output to an external file?

Let's say I have a script outtest.py :

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
d_median = round(median(d), 2)
print(f'median: {d_median}')

Now if I want to capture its output only I know I can just do:

python3 outtest.py > outtest.txt

However, this will only give me an outtest.txt file with e.g.:

mean: 0.34
median: 0.27

What I'm looking for is a way to get an output file like:

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>> mean: 0.34
d_median = round(median(d), 2)
print(f'median: {d_median}')
>> median: 0.27

Or some other format (markdown, whatever). Essentially, something like jupyter notebook or Rmarkdown but with using standard .py files.

Is there any easy way to achieve this?

Body:
You can call the script and inspect its output. You'll have to make some assumptions though. The output is only from stdout, only from lines containing the string "print", and each print produces only one line of output. That being the case, an example command to run it:

> python writer.py script.py

And the script would look like this:

from sys import argv
from subprocess import run, PIPE

script = argv[1]
r = run('python ' + script, stdout=PIPE)
out = r.stdout.decode().split('\n')

with open(script, 'r') as f:
    lines = f.readlines()

with open('out.txt', 'w') as f:
    i = 0
    for line in lines:
        f.write(line)
        if 'print' in line:
            f.write('>>> ' + out[i])
            i += 1

And the output:

import random
from statistics import median, mean

d = [random.random()**2 for _ in range(1000)]
d_mean = round(mean(d), 2)
print(f'mean: {d_mean}')
>>> mean: 0.33
d_median = round(median(d), 2)
print(f'median: {d_median}')
>>> median: 0.24

More complex cases with multiline output or other statements producing output, this won't work. I guess it would require some in depth introspection.


问:
Predicate<T> method equals()
I'm using the interface Predicate<T> from com.google.common.base (Google Guava)

But I don't know how to have the equals() method works...

Why do I get false when I type something like this :

```<code>    Predicate<Object> PredicateD = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    Predicate<Object> PredicateM = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    System.out.println(PredicateD.equals(PredicateM));
</code>```

Thanks in advance for your Help,

答:
You're creating two different anonymous inner classes, but neither of them is overriding equals, so you'll get the default implementation, whereby any two non-equal references are considered non-equal.

As the values of PredicateD and PredicateM are different references, equals returns false.

Title: Predicate<T> method equals()

Body:
I'm using the interface Predicate<T> from com.google.common.base (Google Guava)

But I don't know how to have the equals() method works...

Why do I get false when I type something like this :

    Predicate<Object> PredicateD = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    Predicate<Object> PredicateM = new Predicate<Object>(){
          @Override public boolean apply(Object number) {
                return ((number instanceof Double) && (Math.floor((Double)number) == (Double)number));
            }
    };

    System.out.println(PredicateD.equals(PredicateM));

Thanks in advance for your Help,


Title: How can I get my time strings in a right format?

Body:
I am stuck with converting strings to times. I am aware that there are many topics on Stack regarding converting strings-to-times, however I couldn't fix this problem with the solutions.

Situation
I have a file with times like this:

> dput(df$Time[1:50])
c("1744.3", "2327.54", "1718.51", "2312.3200000000002", "1414.16",
"2046.15", "1442.5", "1912.22", "2303.2199999999998", "2146.3200000000002",
"1459.02", "1930.15", "1856.23", "2319.15", "1451.05", "25.460000000000036",
"1453.25", "2309.02", "2342.48", "2322.5300000000002", "2101.5",
"2026.07", "1245.04", "1945.15", "5.4099999999998545", "1039.5",
"1731.37", "2058.41", "2030.36", "1814.31", "1338.18", "1858.33",
"1731.36", "2343.38", "1733.27", "2304.59", "1309.47", "1916.11",
"1958.3", "1929.54", "1756.4", "1744.23", "1731.26", "1844.47",
"1353.25", "1958.3", "1746.44", "1857.53", "2047.15", "2327.2199999999998", "1915"
)

In this example, the times should be like this:

"1744.3"   = 17:44:30
"2327.54"  = 23:27:54
"1718.51"  = 17:18:51
"2312.3200000000002" = 23:12:32
...
"25.460000000000036" = 00:25:46 # as you can see, the first two 00 are missing.

"1915" = 19:15:00

However, I tried multiple things (and now I am even stuck with str_replace()). Hopefully some one knows how I can transform this.

What have I tried?

format(df$Time, "%H%M.%S") # Yes I know...

# So therefore I thought, lets replace the strings to get them in a proper format
# like HH:MM:SS. First step was to replace the "." for a ":"

str_replace("." , ":", df$Time) # this was leading to "." (don't know why)

And that was the point that I was so frustrated that I posted it on Stack. Hope that you guys can help me.

Many thanks in advance!

Body:
Here is a way to do this, storing the output from dput in x.

library(magrittr)

#Remove all the dots
gsub('\\.', '', x) %>%
  #Select only first 6 characters
  substr(1, 6) %>%
  #Pad 0's at the end
  stringr::str_pad(6,pad = '0', side = 'right') %>%
  #Add colon (:) separator
  sub('(.{2})(.{2})', '\\1:\\2:', .)

# [1] "17:44:30" "23:27:54" "17:18:51" "23:12:32" "14:14:16" "20:46:15"
# [7] "14:42:50" "19:12:22" "23:03:21" "21:46:32" "14:59:02" "19:30:15"
#[13] "18:56:23" "23:19:15" "14:51:05" "25:46:00" "14:53:25" "23:09:02"
#...

Note that this can be done without pipes as well but using it for clarity. From here you can convert the time to POSIXct format if needed.


问:
Is there any limitations for google colab other than the session timeout after 12 hours?
one of the limitations is that we can get only 12 continuous hours per session. Is there any limitations for the usage for GPU and TPU?</p>

答:
From Colab's documentation,

In order to be able to offer computational resources for free, Colab needs to maintain the flexibility to adjust usage limits and hardware availability on the fly. Resources available in Colab vary over time to accommodate fluctuations in demand, as well as to accommodate overall growth and other factors.

In a nutshell, Colab has dynamic resource provisioning. So they can change the hardware, it it is being taxed too much automatically.
Google giveth and Google taketh away.

Link