问:
Is there a way to read request headers in @GraphqQuery method
I need to read data from request header in my graphql query resolver.

Using graphql-spqr library .

method sample.

```<code>import io.leangen.graphql.annotations.*;
import io.leangen.graphql.spqr.spring.annotation.GraphQLApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@GraphQLApi
@Component
public class ProjectQueryResolver{
    @GraphQLQuery
    public Project projects(@GraphqlArugment String projectId) {
        **// want to read authorization token present in request header**
        ...
    }
}
</code>```

答:
Able to resolve using @GraphQLRootContext as one of my method params</p>

```<code>import io.leangen.graphql.annotations.*;
import io.leangen.graphql.spqr.spring.annotation.GraphQLApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@GraphQLApi
@Component
public class ProjectQueryResolver{
    @GraphQLQuery
    public Project projects(@GraphqlArugment String projectId,
                            @GraphQLRootContext DefaultGlobalContext context) {

       HttpServletRequest servletRequest = context.getServletRequest();
       String paramValue = servletRequest.getHeader("param");
       ...
    }
}
</code>```

Body:
I need to read data from request header in my graphql query resolver.

Using graphql-spqr library .

method sample.

import io.leangen.graphql.annotations.*;
import io.leangen.graphql.spqr.spring.annotation.GraphQLApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@GraphQLApi
@Component
public class ProjectQueryResolver{
    @GraphQLQuery
    public Project projects(@GraphqlArugment String projectId) {
        **// want to read authorization token present in request header**
        ...
    }
}

Body:
Able to resolve using @GraphQLRootContext as one of my method params

import io.leangen.graphql.annotations.*;
import io.leangen.graphql.spqr.spring.annotation.GraphQLApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@GraphQLApi
@Component
public class ProjectQueryResolver{
    @GraphQLQuery
    public Project projects(@GraphqlArugment String projectId,
                            @GraphQLRootContext DefaultGlobalContext context) {

       HttpServletRequest servletRequest = context.getServletRequest();
       String paramValue = servletRequest.getHeader("param");
       ...
    }
}


来源: stackexchange

问:
detect aspx website by google
Is there grammar that using google to search for the website build by asp.net. It's like searching the webpages that end with aspx(*.aspx).

Thanks!

答:
Use this search term:

```<code>filetype:aspx
</code>```

This will not find sites using URL rewriting (including MVC sites).

ContentLicense: CC BY-SA 3.0

Title: detect aspx website by google

Body:
Use this search term:

filetype:aspx

This will not find sites using URL rewriting (including MVC sites).


问:
throughput in jmeter convert inkb/s
how do you calculate the throughput in jmter?
and how to convert it to Kb / s?
summary report</p>

答:
Don't you have the throughput in kilobytes per second already?

JMeter automatically stores sent and received bytes into .jtl result files therefore total throughput will be the sum of bytes and sentBytes columns:

More information:

JMeter Glossary

Calculator Class source code

Also don't run your tests in GUI mode, it's for only tests development and debugging, when it comes to test execution you should be running JMeter tests in command-line non-GUI mode and once test execution is finished you can analyze the results using Listeners (use "Browse" button to locate .jtl results file) of your choice or generating HTML Reporting Dashboard

ContentLicense: CC BY-SA 4.0

Title: throughput in jmeter convert inkb/s


问:
KStream issue to read payload coming as before and after in avro format
I am developing KStream application on confluent kafka platform. Data is present on source topic in nested avro format  as mentioned below

```<code>{
   "type":"record",
   "namespace":"xyz",
   "table":"abc",
   "op_type":{
      "string":"D"
   },
   "op_ts":{
      "string":"2020-05-16 09:03:25.000462"
   },
   "pos":{
      "string":"00000000000000010722",
      "before":{
[
            "fields":            {
               "column1":"value"
            },
            {
               "column2":"value"
            },
            {
               "column3":"value"
            }
         ]
      },
      "after":{
[
            "fields":            {
               "column1":"value"
            },
            {
               "column2":"value"
            },
            {
               "column3":"value"
            }
         ]
      }
   }
</code>```

I want to filter records based on op_type="D" as wanted to separate deleted records to other Kafka topic.

I am facing issue to write schema on output topic facing deserialization error : for required row found array.

I have created POJO objects using apache maven-avro plugin.

for "before tag" I mentioned type as array and passing object of before class to it.
Same for "After tag" I mentioned type as array and passing object of after to it.
Rightnow I can not use KSQL here as service is not available in my project.

Need solution how to resolve this nested schema or anyother way to filter deleted records to other kafka topic from source topic.

答:
To resolve above issue, I used generic avro serializer to process data using Kafka streams.

If we use specific avro serializer, we can not filter nested data. Using generic avro serializer will help to filter perticular record with string. I used that and resolved above issue.

Body:
I am developing KStream application on confluent kafka platform. Data is present on source topic in nested avro format  as mentioned below

{
   "type":"record",
   "namespace":"xyz",
   "table":"abc",
   "op_type":{
      "string":"D"
   },
   "op_ts":{
      "string":"2020-05-16 09:03:25.000462"
   },
   "pos":{
      "string":"00000000000000010722",
      "before":{
[
            "fields":            {
               "column1":"value"
            },
            {
               "column2":"value"
            },
            {
               "column3":"value"
            }
         ]
      },
      "after":{
[
            "fields":            {
               "column1":"value"
            },
            {
               "column2":"value"
            },
            {
               "column3":"value"
            }
         ]
      }
   }

I want to filter records based on op_type="D" as wanted to separate deleted records to other Kafka topic.

I am facing issue to write schema on output topic facing deserialization error : for required row found array.

I have created POJO objects using apache maven-avro plugin.

for "before tag" I mentioned type as array and passing object of before class to it.
Same for "After tag" I mentioned type as array and passing object of after to it.
Rightnow I can not use KSQL here as service is not available in my project.

Need solution how to resolve this nested schema or anyother way to filter deleted records to other kafka topic from source topic.


问:
XSD specifying a table (all elements) should be filled completely or not at all?
I am looking for a solution within the XML 1.0 constraints to specify in XSD schema that a table should be filled completely or not at all. The table is optional and only needs to be filled when applicable, but if applicable all elements in the table are mandatory. I tried with specifying the table with minOccurrences = "0" and the elements within the table with minOccurrences = "1", but then I always have to provide a value for those elements.

答:
The table is optional

So, minOccurs="0" on the table element.

and only needs to be filled when applicable

Some applicability constraints are not expressible in XSD 1.0.

If you can upgrade to XSD 1.1, you could use assertions to specify criteria for which the table cells may or may not be empty.

but if applicable all elements in the table are mandatory.

If the only applicability constraint is that the table cells must have content, you can accomplish the all-or-nothing aspect of your requirement with simple minOccurs="0" on the table and minOccurs="1" on cells.  So, if the table is there, the cells must be there.  You can also require that the cells be non-empty.  All of this can be done in XSD 1.0.

More complex applicability constraints may require XSD 1.1 assertions.

See this answer for how to use xs:assert to specify conditions via every...satisfies that must be true over table cells.


问:
How to plot an RGB image using the image() function from a 3D array?
I have an array with dimension (28,28,3) height, width, depth. Each depth is one of the RGB channels. The values are between 0 and 1.

I want to use the image() function to plot the image. The z argument is a matrix. How can I convert the array into a matrix in order to be able to plot?

My final goal is to have something like this but with color images.

答:
With the raster package you can do</p>

```<code>R <- matrix(rep(sin(seq(0, 2*pi, length.out = 31))^2, length.out = 900), nrow = 30)
G <- matrix(rep(cos(seq(0, 2*pi, length.out = 15))^2, length.out = 900), nrow = 30)
B <- matrix(rep(sin(seq(pi, 2*pi, length.out = 30))^2, length.out = 900), nrow = 30)

my_img <- c(R, G, B)
dim(my_img) <- c(30, 30, 3)

library(raster)
b <- brick(my_img)
crs(b) <- "+proj=tmerc"
plotRGB(b, scale=1)
# or
plotRGB(b, scale=1, interpolate=TRUE)
</code>```

Body:
With the raster package you can do

R <- matrix(rep(sin(seq(0, 2*pi, length.out = 31))^2, length.out = 900), nrow = 30)
G <- matrix(rep(cos(seq(0, 2*pi, length.out = 15))^2, length.out = 900), nrow = 30)
B <- matrix(rep(sin(seq(pi, 2*pi, length.out = 30))^2, length.out = 900), nrow = 30)

my_img <- c(R, G, B)
dim(my_img) <- c(30, 30, 3)

library(raster)
b <- brick(my_img)
crs(b) <- "+proj=tmerc"
plotRGB(b, scale=1)
# or
plotRGB(b, scale=1, interpolate=TRUE)


问:
Compare future date with current date SwiftUI
I have the following:

```<code>struct ContentView: View {
var body: some View {
    VStack{
        Button(action: {
            let soon = Date().addingTimeInterval(100)

            if(soon == Date()) {
                print("Time is up!")
            }
        }) {
            Text("Alert")
        }
    }
}
}
</code>```

I'm trying to add some time to soon and then when the current time is == to soon, then execute the print, how can I do that?

What I want is: I have current time, then I add some seconds to that time and when that time is up do something, I need Date() because I'll be working with specific times, for example, if it's 10am, I want to add 3 min, then when it's 10:03am display alert.

答:
What I did was to create an onReceive and then do the check there:

```<code>.onReceive(self.timer) { _ in
    if(self.now > dateInTime) {
    ...
    }
}
</code>```

Then on the actual view I can check if "overdue" then do whatever I want.

Body:
I have the following:

struct ContentView: View {
var body: some View {
    VStack{
        Button(action: {
            let soon = Date().addingTimeInterval(100)

            if(soon == Date()) {
                print("Time is up!")
            }
        }) {
            Text("Alert")
        }
    }
}
}

I'm trying to add some time to soon and then when the current time is == to soon, then execute the print, how can I do that?

What I want is: I have current time, then I add some seconds to that time and when that time is up do something, I need Date() because I'll be working with specific times, for example, if it's 10am, I want to add 3 min, then when it's 10:03am display alert.

Body:
What I did was to create an onReceive and then do the check there:

.onReceive(self.timer) { _ in
    if(self.now > dateInTime) {
    ...
    }
}

Then on the actual view I can check if "overdue" then do whatever I want.


问:
Cannot run tomcat7:run in maven project
working on a maven project I get the following error when I try to 'mvn tomcat7:run' so to start the app in an embed tomcat.

I have searched SO answers in similar questions but nothing solves the issue.

Tomcat plugin: tomcat7-maven-plugin v2.2

Could this be due to maven libraries version mismatch?

```<code>    SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.11.0/jackson-annotations-2.11.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Jun 02, 2020 8:07:44 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.11.0.rc1/jackson-core-2.11.0.rc1.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Jun 02, 2020 8:07:44 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/jakarta/ws/rs/jakarta.ws.rs-api/2.1.6/jakarta.ws.rs-api-2.1.6.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Jun 02, 2020 8:07:46 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.11.0/jackson-databind-2.11.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

答:
I don't see the  version but based on your command if you are using tomcat7 you may need to upgrade, see:

Invalid byte tag in constant pool: 19 error message

Title: Cannot run tomcat7:run in maven project

Body:
working on a maven project I get the following error when I try to 'mvn tomcat7:run' so to start the app in an embed tomcat.

I have searched SO answers in similar questions but nothing solves the issue.

Tomcat plugin: tomcat7-maven-plugin v2.2

Could this be due to maven libraries version mismatch?

    SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.11.0/jackson-annotations-2.11.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Jun 02, 2020 8:07:44 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.11.0.rc1/jackson-core-2.11.0.rc1.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Jun 02, 2020 8:07:44 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/jakarta/ws/rs/jakarta.ws.rs-api/2.1.6/jakarta.ws.rs-api-2.1.6.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Jun 02, 2020 8:07:46 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/Users/George/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.11.0/jackson-databind-2.11.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
        at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133)
        at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
        at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976)
        at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)


问:
log4net is logging all levels, instead of what I've configured it to do
I have the level set to "INFO" but I'm seeing DEBUG events in the log.

Config

<?xml version="1.0"?>

<configuration>
    <configSections>

    </configSections>

    <log4net>
        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
            <level value="INFO"/>
            <file value="Logs\Log.txt" />
            <appendToFile value="true" />
            <rollingStyle value="Size" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="10MB" />
            <staticLogFileName value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
        </appender>

        <root>
            <appender-ref ref="RollingFileAppender"/>
        </root>
    </log4net>
</configuration>
```

<h3>Code</h3>

```private ILog Log { get; set; }

static Program()
{
    XmlConfigurator.Configure();
    //...
    this.Log.Info("Started in RunOnce mode.");
}
```

答: I think that within your root tag you need to set the property <level value="INFO"> for your appender.

Body:
I have the level set to "INFO" but I'm seeing DEBUG events in the log.

Config

<?xml version="1.0"?>

<configuration>
    <configSections>

    </configSections>

    <log4net>
        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
            <level value="INFO"/>
            <file value="Logs\Log.txt" />
            <appendToFile value="true" />
            <rollingStyle value="Size" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="10MB" />
            <staticLogFileName value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
        </appender>

        <root>
            <appender-ref ref="RollingFileAppender"/>
        </root>
    </log4net>
</configuration>

Code

private ILog Log { get; set; }

static Program()
{
    XmlConfigurator.Configure();
    //...
    this.Log.Info("Started in RunOnce mode.");
}


问:
How to specify rotated file location by using rotating-file-stream
I have writtten code like below to log express logs.

```<code>const rfs = require("rotating-file-stream");

function formatDate() {
  var d = new Date(),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();
    hour = d.getHours();

  if (month.length < 2)
    month = '0' + month;
  if (day.length < 2)
    day = '0' + day;
  if (hour.length < 2)
    hour = '0' + hour

  return [year, month, day, hour].join('-');
}

let log_directory = '/../logs/';

let log_date = formatDate()
let log_file_name =  path.normalize(__dirname + log_directory + log_date, 'access.log');

let accessLogStream = rfs.createStream(log_file_name, {
  size: "300M",
  interval: "1d",
})

app.use(morgan(':date[iso] :method :url :body :headers :remote-addr :req[content-length] - :status :response-time ms - :res[content-length] ', { stream: accessLogStream }));
</code>```

logs are getting stored out side of the project as expected.

But after rotation, the logs are storing inside the project with the below folder names

```<code>20200507-0943-01-
20200508-0943-01-
20200509-0943-01-
20200510-0943-01-
20200511-0943-01-
20200512-0943-01-
20200513-0944-01-
package.json
package-lock.json
public
routes
scripts
services
app.js
</code>```

I don't want these folders created inside the project. Is there any way to handle this?

答:
First of all you are using a static file name as filename parameter of createStream function and you are doing some computation on date to have your resulting file name.

Please note that the computation on date happens only once, before calling the createStream function. In order to do computation on date happening at each rotation you should use a filename generator function. Details can be found in readme.

More than this it seems there is a bug in this line: path.normalize accepts only one parameter.

```<code>let log_file_name =  path.normalize(__dirname + log_directory + log_date, 'access.log');
</code>```

Last, to specify a directory for logging, path option should be enough.

If I argued correctly your intentions, following code should solve all the problems

```<code>const rfs = require("rotating-file-stream");

function formatDate(d) {
  var month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear(),
    hour = d.getHours();

  if (month.length < 2)
    month = '0' + month;
  if (day.length < 2)
    day = '0' + day;
  if (hour.length < 2)
    hour = '0' + hour;

  return [year, month, day, hour].join('-');
}

function log_file_name(time, index) {
  if (!time) return 'access.log';

  return [formatDate(time), index, 'access.log'].join('-');
}

let accessLogStream = rfs.createStream(log_file_name, {
  size: "300M",
  interval: "1d",
  path: '/../logs/'
});
</code>```

Body:
I have writtten code like below to log express logs.

const rfs = require("rotating-file-stream");

function formatDate() {
  var d = new Date(),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();
    hour = d.getHours();

  if (month.length < 2)
    month = '0' + month;
  if (day.length < 2)
    day = '0' + day;
  if (hour.length < 2)
    hour = '0' + hour

  return [year, month, day, hour].join('-');
}

let log_directory = '/../logs/';

let log_date = formatDate()
let log_file_name =  path.normalize(__dirname + log_directory + log_date, 'access.log');

let accessLogStream = rfs.createStream(log_file_name, {
  size: "300M",
  interval: "1d",
})

app.use(morgan(':date[iso] :method :url :body :headers :remote-addr :req[content-length] - :status :response-time ms - :res[content-length] ', { stream: accessLogStream }));

logs are getting stored out side of the project as expected.

But after rotation, the logs are storing inside the project with the below folder names

20200507-0943-01-
20200508-0943-01-
20200509-0943-01-
20200510-0943-01-
20200511-0943-01-
20200512-0943-01-
20200513-0944-01-
package.json
package-lock.json
public
routes
scripts
services
app.js

I don't want these folders created inside the project. Is there any way to handle this?

Body:
First of all you are using a static file name as filename parameter of createStream function and you are doing some computation on date to have your resulting file name.

Please note that the computation on date happens only once, before calling the createStream function. In order to do computation on date happening at each rotation you should use a filename generator function. Details can be found in readme.

More than this it seems there is a bug in this line: path.normalize accepts only one parameter.

let log_file_name =  path.normalize(__dirname + log_directory + log_date, 'access.log');

Last, to specify a directory for logging, path option should be enough.

If I argued correctly your intentions, following code should solve all the problems

const rfs = require("rotating-file-stream");

function formatDate(d) {
  var month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear(),
    hour = d.getHours();

  if (month.length < 2)
    month = '0' + month;
  if (day.length < 2)
    day = '0' + day;
  if (hour.length < 2)
    hour = '0' + hour;

  return [year, month, day, hour].join('-');
}

function log_file_name(time, index) {
  if (!time) return 'access.log';

  return [formatDate(time), index, 'access.log'].join('-');
}

let accessLogStream = rfs.createStream(log_file_name, {
  size: "300M",
  interval: "1d",
  path: '/../logs/'
});


问:
<Grid> in material ui causes horizontal scroll- React
I'm using Material-UI version 1. installed by this command:

```<code>npm install -S material-ui@next
</code>```

Everytime I want to use , an unwanted horizontal scroll appears in the page.

Code:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles, createStyleSheet } from 'material-ui/styles';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';

/* project imports */
import NavMenu from './Page-Parts/NavMenu';
import LoginPanel from './Login-Parts/LoginPanel';

const styleSheet = createStyleSheet('FullWidthGrid', theme => ({
  root: {
    flexGrow: 1,
    marginTop: 0,
  },
  paper: {
    padding: 16,
    textAlign: 'center',
    color: theme.palette.text.secondary,
    marginTop: "3rem"
  },
}));

function Login(props) {
    const classes = props.classes;
    return (
    <div className={classes.root}>
      <Grid container gutter={24} justify='center'>
        <Grid item xs={12} md={12} sm={12} lg={12}>
          <NavMenu/>
        </Grid>
        <Grid item xs={6} sm={6} md={6} lg={6}>
          <Paper className={classes.paper}>
            <LoginPanel />
          </Paper>
        </Grid>
      </Grid>
    </div>
    );
}

Login.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styleSheet)(Login);
</code>```

Bootstrap and other grid layout options are in conflict with this library. When I use <Grid> in other parts of a component(for example in drawer), horizontal scroll appears makes the UI ugly
NavMenu and LoginPanel are some self-made components and they work and using them without  doesn't cause horizontal scroll.

答:
I was facing the same issue. Remove spacing from the Grid container didn't solve it.

Solution:

Instead of setting with on the parent of the Grid container, setting maxWidth fixes the issues and assigns the desired width. For example, if we set maxWidth on the Box that is the parent of Grid container, then the Grid doesn't overflows horizontally.

We don't need to set width 100% on the Grid container because its purpose is to adapt to 100% width by default.

```<code> <Box style={{ maxWidth: 600}}>
     <Grid container spacing={3}>
     ...
     </Grid>
 </Box>
</code>```

Body:
I'm using Material-UI version 1. installed by this command:

npm install -S material-ui@next

Everytime I want to use , an unwanted horizontal scroll appears in the page.

Code:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles, createStyleSheet } from 'material-ui/styles';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';

/* project imports */
import NavMenu from './Page-Parts/NavMenu';
import LoginPanel from './Login-Parts/LoginPanel';

const styleSheet = createStyleSheet('FullWidthGrid', theme => ({
  root: {
    flexGrow: 1,
    marginTop: 0,
  },
  paper: {
    padding: 16,
    textAlign: 'center',
    color: theme.palette.text.secondary,
    marginTop: "3rem"
  },
}));

function Login(props) {
    const classes = props.classes;
    return (

      <Grid container gutter={24} justify='center'>
        <Grid item xs={12} md={12} sm={12} lg={12}>
          <NavMenu/>
        </Grid>
        <Grid item xs={6} sm={6} md={6} lg={6}>
          <Paper className={classes.paper}>
            <LoginPanel />
          </Paper>
        </Grid>
      </Grid>

    );
}

Login.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styleSheet)(Login);

Bootstrap and other grid layout options are in conflict with this library. When I use <Grid> in other parts of a component(for example in drawer), horizontal scroll appears makes the UI ugly
NavMenu and LoginPanel are some self-made components and they work and using them without  doesn't cause horizontal scroll.

Body:
I was facing the same issue. Remove spacing from the Grid container didn't solve it.

Solution:

Instead of setting with on the parent of the Grid container, setting maxWidth fixes the issues and assigns the desired width. For example, if we set maxWidth on the Box that is the parent of Grid container, then the Grid doesn't overflows horizontally.

We don't need to set width 100% on the Grid container because its purpose is to adapt to 100% width by default.

 <Box style={{ maxWidth: 600}}>
     <Grid container spacing={3}>
     ...
     </Grid>
 </Box>


问:
How do I insert
 tag in Arabic Left to Right (LTR) text
I have this Arabic sample text:

```<code><span class="message4" id="message4" data-gwd-tl-locked="" data-gwd-tl-hidden="">نص العنوان الرئيسي هنا <br> على سطرين</span>
</code>```

I managed to copy paste a line break in there. Actually I pasted it in between two other words but it moved towards the right.

I got no clue what is going on, sorry. Is it even possible to get a line break into ARABIC text? And why does it, like a wild chicken, move position when I paste it into a location.

Should I just make my containers reflow text and skip line break for ARABIC?

Thanks in Advance

Thomas

答:
I tried this out in VSCode, and I see what you're seeing, but it seems to mostly be bugs in VSCode. For example, VSCode can get very confused when you select sections of Arabic text and reformat the text as you select. (I can almost picture the mistakes in the code that probably lead to this, I assume by laying out the highlighted text separately from the non-highlighted text rather than laying it all out and then highlighting part of it.)

What I recommend, if you can get away with it, is to put LTR and RTL text on separate lines:

```<code><span class="message4" id="message4" data-gwd-tl-locked="" data-gwd-tl-hidden="">
نص العنوان الرئيسي هنا
<br/>
على سطرين
</span>
</code>```

This formatting tends to be easier for bidi (bidirectional text) algorithms to deal with, and makes it more clear that this is "نص العنوان الرئيسي هنا" and then a break, and then "على سطرين". When you put these on a single line, it is very non-obvious, at least to me, what order the phrases are supposed to be. Is this Latin text with Arabic in the middle, or Arabic text with Latin in the middle? Adding newlines makes it much clearer IMO.

Title: How do I insert <br> tag in Arabic Left to Right (LTR) text

Body:
I have this Arabic sample text:

نص العنوان الرئيسي هنا
 على سطرين

I managed to copy paste a line break in there. Actually I pasted it in between two other words but it moved towards the right.

I got no clue what is going on, sorry. Is it even possible to get a line break into ARABIC text? And why does it, like a wild chicken, move position when I paste it into a location.

Should I just make my containers reflow text and skip line break for ARABIC?

Thanks in Advance

Thomas

Body:
I tried this out in VSCode, and I see what you're seeing, but it seems to mostly be bugs in VSCode. For example, VSCode can get very confused when you select sections of Arabic text and reformat the text as you select. (I can almost picture the mistakes in the code that probably lead to this, I assume by laying out the highlighted text separately from the non-highlighted text rather than laying it all out and then highlighting part of it.)

What I recommend, if you can get away with it, is to put LTR and RTL text on separate lines:

<span class="message4" id="message4" data-gwd-tl-locked="" data-gwd-tl-hidden="">
نص العنوان الرئيسي هنا
<br/>
على سطرين
</span>

This formatting tends to be easier for bidi (bidirectional text) algorithms to deal with, and makes it more clear that this is "نص العنوان الرئيسي هنا" and then a break, and then "على سطرين". When you put these on a single line, it is very non-obvious, at least to me, what order the phrases are supposed to be. Is this Latin text with Arabic in the middle, or Arabic text with Latin in the middle? Adding newlines makes it much clearer IMO.


问:
Read normal text on webpage with Python
I wonder if there a way to read the text of a webpage to compare to other values,like this
webpage: "Tacos"
Python program: </p>

```<code>x=the webpage text
 if x == 'Tacos':
 print('The text is: ', x)
</code>```

答:
Web scraping is a very common task to do with Python. If you have a direct link to the webpage you want to get the text from, then you can use get requests to get the HTML:

```<code>from requests import get

html_as_text = get(url_to_webpage).text
</code>```

and then you can use BeautifulSoup to parse it:

```<code>from bs4 import BeautifulSoup
html = BeautifulSoup(html_as_text, 'html.parser')
print(html.prettify())
</code>```

if you don't have a direct link to the webpage, you can use something like Selenium to navigate to it.

Title: Read normal text on webpage with Python

Body:
I wonder if there a way to read the text of a webpage to compare to other values,like this
webpage: "Tacos"
Python program:

x=the webpage text
 if x == 'Tacos':
 print('The text is: ', x)

Body:
Web scraping is a very common task to do with Python. If you have a direct link to the webpage you want to get the text from, then you can use get requests to get the HTML:

from requests import get

html_as_text = get(url_to_webpage).text

and then you can use BeautifulSoup to parse it:

from bs4 import BeautifulSoup
html = BeautifulSoup(html_as_text, 'html.parser')
print(html.prettify())

if you don't have a direct link to the webpage, you can use something like Selenium to navigate to it.


问:
ESLint with TypeScript parser/plugin: how to include .spec.ts, that is excluded from tsconfig.json?
I'm using the awesome typescript-eslint together with ESLint.

Problem description: the TypeScript ESLint parser complains about src/module.spec.ts not being part of the project, and this is correct. I'm excluding all spec.ts files from TypeScript tsconfig.json file because they don't need to be transpiled.

How to make src/module.spec.ts not transplied but still checked against ESLint?

my-project\src\module.spec.ts
  0:0  error  Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
  The file does not match your project config: src\module.spec.ts.
  The file must be included in at least one of the projects provided

My .eslint.json (stripped down):

```<code>{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "env": {
    "node": true
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "project": "tsconfig.json"
  },
  "plugins": [
    "@typescript-eslint"
  ]
}
</code>```

My tsconfig.json:

```<code>{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "sourceMap": false,
    "outDir": "./dist",
    "rootDir": "./src",
    "removeComments": true,
    "strict": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "./dist",
    "**/*.spec.ts"
  ]
}
</code>```

答:
In the project folder containing tsconfig.json, create another JSON file with the following contents:

```<code>{
  "exclude": [
    "./dist"
  ],
  "extends": "./tsconfig.json"
}
</code>```

The exact file name is irrelevant here. Note that this is a perfectly valid TypeScript configuration file where all settings are inherited from ./tsconfig.json, execept for extends, where the pattern "**/*.spec.ts" has been removed.

A tool that reads its settings from this new JSON file (as opposed to the default tsconfig.json) will not ignore src/module.spec.ts.

Then in your .eslint.json under parserOptions set the name of the new JSON file as project, e.g. if the file is called test.tsconfig.json:

```<code>"project": "test.tsconfig.json"
</code>```

Then run ESLint and see what else it's complaining about.

This is basically what I'm doing in one of my projects having encountered a similar problem. There must be probably a few other ways to achieve the same effect.

Body:
I'm using the awesome typescript-eslint together with ESLint.

Problem description: the TypeScript ESLint parser complains about src/module.spec.ts not being part of the project, and this is correct. I'm excluding all spec.ts files from TypeScript tsconfig.json file because they don't need to be transpiled.

How to make src/module.spec.ts not transplied but still checked against ESLint?

my-project\src\module.spec.ts
  0:0  error  Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
  The file does not match your project config: src\module.spec.ts.
  The file must be included in at least one of the projects provided

My .eslint.json (stripped down):

{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "env": {
    "node": true
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "project": "tsconfig.json"
  },
  "plugins": [
    "@typescript-eslint"
  ]
}

My tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "sourceMap": false,
    "outDir": "./dist",
    "rootDir": "./src",
    "removeComments": true,
    "strict": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "./dist",
    "**/*.spec.ts"
  ]
}

Body:
In the project folder containing tsconfig.json, create another JSON file with the following contents:

{
  "exclude": [
    "./dist"
  ],
  "extends": "./tsconfig.json"
}

The exact file name is irrelevant here. Note that this is a perfectly valid TypeScript configuration file where all settings are inherited from ./tsconfig.json, execept for extends, where the pattern "**/*.spec.ts" has been removed.

A tool that reads its settings from this new JSON file (as opposed to the default tsconfig.json) will not ignore src/module.spec.ts.

Then in your .eslint.json under parserOptions set the name of the new JSON file as project, e.g. if the file is called test.tsconfig.json:

"project": "test.tsconfig.json"

Then run ESLint and see what else it's complaining about.

This is basically what I'm doing in one of my projects having encountered a similar problem. There must be probably a few other ways to achieve the same effect.


问:
Simplest way to check if two integers have same sign?
Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?</p>

答:
branchless C version:

```<code>int sameSign(int a, int b) {
    return ~(a^b) & (1<<(sizeof(int)*8-1));
}
</code>```

C++ template for integer types:

```<code>template <typename T> T sameSign(T a, T b) {
    return ~(a^b) & (1<<(sizeof(T)*8-1));
}
</code>```

OwnerDisplayName: Gerber

ContentLicense: CC BY-SA 2.5

Body:
branchless C version:

int sameSign(int a, int b) {
    return ~(a^b) & (1<<(sizeof(int)*8-1));
}

C++ template for integer types:

template <typename T> T sameSign(T a, T b) {
    return ~(a^b) & (1<<(sizeof(T)*8-1));
}


问:
Adjustable row heights with bootstrap 4
I'm using bootstrap columns to display expanding cards.  When one expands though, it pushes the whole row underneath it down.

Unexpanded:

Currently how it behaves expanded:

How I'd like it to behave:

I've been reading about flexbox, but I cant find any good examples of the desired behavior, while maintaining responsive design.

Currently the code is along the lines of

```<code><div class="row">
    <div class="col-xl-4 col-lg-5 col-12">
        expanding content...
    </div>
    .
    .
    .
    <div class="col-xl-4 col-lg-5 col-12">
        expanding content...
    </div>
</div>
</code>```

答:
I see 2 possibilities:

1. Solution: Have you checked out the bootstrap-component card-columns? It organizes the cards into Masonry-like columns.
By using

```<code>.card-columns {
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
}
</code>```

you can make them responsive.

2. Solution:
You use just 3 cols:

.row {
  margin-top: 20px;
  align-content: flex-start;
}

.card {
  padding: 10px;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">

<div class="col-4">

 <div class="card">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip.
 </div><!-- card -->

    <div class="card">
        Lorem
 </div><!-- card -->

</div><!-- col -->

<div class="col-4">

 <div class="card">
        Lorem
 </div><!-- card -->

    <div class="card">
        Lorem
 </div><!-- card -->

</div><!-- col -->

<div class="col-4">

 <div class="card">
        Lorem
 </div><!-- card -->

    <div class="card">
        Lorem
 </div><!-- card -->

</div><!-- col -->
</div><!--row --></code>```

Title: Adjustable row heights with bootstrap 4

Body:
I'm using bootstrap columns to display expanding cards.  When one expands though, it pushes the whole row underneath it down.

Unexpanded:

Currently how it behaves expanded:

How I'd like it to behave:

I've been reading about flexbox, but I cant find any good examples of the desired behavior, while maintaining responsive design.

Currently the code is along the lines of

        expanding content...

    .
    .
    .

        expanding content...

Body:
I see 2 possibilities:

1. Solution: Have you checked out the bootstrap-component card-columns? It organizes the cards into Masonry-like columns.
By using

.card-columns {
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
}

you can make them responsive.

2. Solution:
You use just 3 cols:

.row {
  margin-top: 20px;
  align-content: flex-start;
}

.card {
  padding: 10px;
  margin-bottom: 10px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">

<div class="col-4">

 <div class="card">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip.
 </div><!-- card -->

    <div class="card">
        Lorem
 </div><!-- card -->

</div><!-- col -->

<div class="col-4">

 <div class="card">
        Lorem
 </div><!-- card -->

    <div class="card">
        Lorem
 </div><!-- card -->

</div><!-- col -->

<div class="col-4">

 <div class="card">
        Lorem
 </div><!-- card -->

    <div class="card">
        Lorem
 </div><!-- card -->

</div><!-- col -->
</div><!--row -->


问:
Apply function based on value in other column
I have a dataframe that contains 10 observation per unique ID and some other variables. Unfortunately, the data has some missing values (NA's) for a specific column that I want to replace by carrying the last observation forward (by means of the na.locf function of the zoo package).

The thing is, I need to perform this function per unique user, so I need to "split" the dataframe per unique ID, and then apply the function, while keeping all other columns. I have tried the following, but this did not work:

```<code>df %>%
  group_by(ID) %>%
  group_split() %>%
  lapply(Location, na.locf() %>%
  bind_rows
</code>```

A reproducible example of the dataset:

```<code>ID <- rep(1:5, each = 10)
Age <- sample(18:65, 50, replace = TRUE)
Locations <- c("Europe", "Asia", NA)
Location <- sample(Location, 50, replace = TRUE)
df <- data.frame(ID, Age, Location)
</code>```

答:
Using group_by then na.locf, with the na.rm=FALSE option to keep the length of the output:

```<code>library(dplyr)
df <- df %>% group_by(ID) %>%
mutate(Location=zoo::na.locf(Location, na.rm=FALSE))
</code>```

As Martin commented, if the series starts with a missing value for a given ID, it will not be filled. This script does not fail, even when the series starts with a missing. For instance:

```<code>df <- tibble(ID=c(1, 1, 2, 2), Location=c(NA,"Europe","Asia",NA))
df %>% group_by(ID) %>% mutate(Location2=zoo::na.locf(Location, na.rm=FALSE))
</code>```

returns:

```<code># A tibble: 4 x 3
# Groups:   ID [2]
     ID Location Location2
  <dbl> <chr>    <chr>
1     1 <NA>     <NA>
2     1 Europe   Europe
3     2 Asia     Asia
4     2 <NA>     Asia
</code>```

Body:
I have a dataframe that contains 10 observation per unique ID and some other variables. Unfortunately, the data has some missing values (NA's) for a specific column that I want to replace by carrying the last observation forward (by means of the na.locf function of the zoo package).

The thing is, I need to perform this function per unique user, so I need to "split" the dataframe per unique ID, and then apply the function, while keeping all other columns. I have tried the following, but this did not work:

df %>%
  group_by(ID) %>%
  group_split() %>%
  lapply(Location, na.locf() %>%
  bind_rows

A reproducible example of the dataset:

ID <- rep(1:5, each = 10)
Age <- sample(18:65, 50, replace = TRUE)
Locations <- c("Europe", "Asia", NA)
Location <- sample(Location, 50, replace = TRUE)
df <- data.frame(ID, Age, Location)

Body:
Using group_by then na.locf, with the na.rm=FALSE option to keep the length of the output:

library(dplyr)
df <- df %>% group_by(ID) %>%
mutate(Location=zoo::na.locf(Location, na.rm=FALSE))

As Martin commented, if the series starts with a missing value for a given ID, it will not be filled. This script does not fail, even when the series starts with a missing. For instance:

df <- tibble(ID=c(1, 1, 2, 2), Location=c(NA,"Europe","Asia",NA))
df %>% group_by(ID) %>% mutate(Location2=zoo::na.locf(Location, na.rm=FALSE))

returns:

# A tibble: 4 x 3
# Groups:   ID [2]
     ID Location Location2
  <dbl> <chr>    <chr>
1     1 <NA>     <NA>
2     1 Europe   Europe
3     2 Asia     Asia
4     2 <NA>     Asia


问:
Failed to start Freeswitch in centos?
I have just installed Freeswitch in Centos7 . when i check my Freeswitch status , its failing to start with following error. Any help would be highly appreciated.

I have attached copy of both command and the logs file showing errors as well

Starting freeswitch

```<code> [root@localhost log]# systemctl start freeswitch
 [root@localhost log]# systemctl status freeswitch
</code>```

```<code>    ●Started FreeSWITCH.
</code>```

```<code> Feb 17 22:56:38 localhost freeswitch: ERROR: Failed to set SCHED_FIFO scheduler (Operation not permitted)
    Feb 17 22:56:38 localhost freeswitch: ERROR: Could not set nice level
    Feb 17 22:56:38 localhost freeswitch: Cannot open pid file /opt/freeswitch/run/freeswitch.pid.
    Feb 17 22:56:38 localhost systemd: freeswitch.service: main process exited, code=exited, status=255/n/a
    Feb 17 22:56:38 localhost systemd: Unit freeswitch.service entered failed state.
    Feb 17 22:56:38 localhost systemd: freeswitch.service failed.
</code>```

答:
```<code>ps aux | grep freeswitch
</code>```

Check whether a freeswitch is already running so it can't open the pid file:

```<code>/opt/freeswitch/run/freeswitch.pid
</code>```

If there is a freeswitch already running, kill it:

```<code>kill 9 {pid}
</code>```

Title: Failed to start Freeswitch in centos?

Body:
I have just installed Freeswitch in Centos7 . when i check my Freeswitch status , its failing to start with following error. Any help would be highly appreciated.

I have attached copy of both command and the logs file showing errors as well

Starting freeswitch

 [root@localhost log]# systemctl start freeswitch
 [root@localhost log]# systemctl status freeswitch

    ●Started FreeSWITCH.

 Feb 17 22:56:38 localhost freeswitch: ERROR: Failed to set SCHED_FIFO scheduler (Operation not permitted)
    Feb 17 22:56:38 localhost freeswitch: ERROR: Could not set nice level
    Feb 17 22:56:38 localhost freeswitch: Cannot open pid file /opt/freeswitch/run/freeswitch.pid.
    Feb 17 22:56:38 localhost systemd: freeswitch.service: main process exited, code=exited, status=255/n/a
    Feb 17 22:56:38 localhost systemd: Unit freeswitch.service entered failed state.
    Feb 17 22:56:38 localhost systemd: freeswitch.service failed.

Body:
ps aux | grep freeswitch

Check whether a freeswitch is already running so it can't open the pid file:

/opt/freeswitch/run/freeswitch.pid

If there is a freeswitch already running, kill it:

kill 9 {pid}


问:
How to sort on multiple columns using JavaScript sort?
I have following array that needs to be sorted with respect to search text 'John'.

```<code>  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 5, firstName: 'John', lastName: 'Doe'},

];
</code>```

Expected Output:

Array should be first sorted with nickName (with search text) then lastName(with search text). If nickName is not present then it should sorted with respect to firstName(with search text) with ASC sorting order.
Note: It should consider search text word as 'John'

This sort resembles like Search with Sort in your mobile's contact app

```<code>[
  // sort with nickName as higher relevance considering search text as John
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  // sort with lastName considering search text
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  // sort  with firstName as nickName is null
  {id: 5, firstName: 'John', lastName: 'Doe'},

];
</code>```

I tried localeMethod

```<code>function sortByLocale(user1, user2) {
   var sortByNickName = user1.nickName.toLowerCase().localeCompare(user2.nickName.toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortByNickName || sortByLastName;
}
</code>```

But the result is not considering search text while sorting.
One approach, I can see is creating three different arrays and sort them and combined those sorted array
Any helps would be appreciated.

Edit: Not considering the non-matched object with search text value

答:
Just add first search by name</p>

```<code>function checkSearch (value)  {
   return (value.nickName === 'John') * -3 ||
      (value.lastName === 'John') * -2 ||
      (value.firstName === 'John') * -1 ||
      0
}

function sortByLocale(user1, user2) {
   var sortBySearch = checkSearch(user1) - checkSearch(user2)

   var sortByNickName = (user1.nickName || '').toLowerCase().localeCompare((user2.nickName || '').toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortBySearch || sortByNickName || sortByLastName;
}
</code>```

Body:
I have following array that needs to be sorted with respect to search text 'John'.

  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 5, firstName: 'John', lastName: 'Doe'},

];

Expected Output:

Array should be first sorted with nickName (with search text) then lastName(with search text). If nickName is not present then it should sorted with respect to firstName(with search text) with ASC sorting order.
Note: It should consider search text word as 'John'

This sort resembles like Search with Sort in your mobile's contact app

[
  // sort with nickName as higher relevance considering search text as John
  {id: 4, firstName: 'Test', lastName: 'Mason', nickName: 'John'},
  {id: 3, firstName: 'Test', lastName: 'Zch', nickName: 'John'},
  // sort with lastName considering search text
  {id: 2, firstName: 'Test', lastName: 'John', nickName: 'Andrew'},
  {id: 1, firstName: 'User', lastName: 'John', nickName: 'Smith'},
  // sort  with firstName as nickName is null
  {id: 5, firstName: 'John', lastName: 'Doe'},

];

I tried localeMethod

function sortByLocale(user1, user2) {
   var sortByNickName = user1.nickName.toLowerCase().localeCompare(user2.nickName.toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortByNickName || sortByLastName;
}

But the result is not considering search text while sorting.
One approach, I can see is creating three different arrays and sort them and combined those sorted array
Any helps would be appreciated.

Edit: Not considering the non-matched object with search text value

Body:
Just add first search by name

function checkSearch (value)  {
   return (value.nickName === 'John') * -3 ||
      (value.lastName === 'John') * -2 ||
      (value.firstName === 'John') * -1 ||
      0
}

function sortByLocale(user1, user2) {
   var sortBySearch = checkSearch(user1) - checkSearch(user2)

   var sortByNickName = (user1.nickName || '').toLowerCase().localeCompare((user2.nickName || '').toLowerCase());
   var sortByLastName = user1.lastName.toLowerCase().localeCompare(user2.lastName.toLowerCase());

   return sortBySearch || sortByNickName || sortByLastName;
}


问:
Laravel 5.3 Migration: 1215 Cannot add foreign key constraint
I'm using Laravel 5.3 and I'm trying to create  FK, however when I migrate my table using artisan I'm getting the following error:

```<code>  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `topic_video` add constraint `topic_video_vendor_id_foreign` foreign key (`vendor_id`) references `vendors` (`id`))

  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
</code>```

I have tried multiple solutions on SOF for different laravel versions but none of them work.

This is my topic_video table (InnoDB)

This is an old and big project, as I don't have migrations for it, only for new tables we have migrations. So I have created a vendors (MyISAM)

```<code>Schema::create('vendors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('channel_url');
            $table->timestamps();
        });
</code>```

Then I have add FK of above migration to topic_video table.

```<code>Schema::table('topic_video', function (Blueprint $table) {
            $table->integer('vendor_id')->unsigned()->nullable();
            $table->foreign('vendor_id')->references('id')->on('vendors');
        });
</code>```

I have tried without unsigned(), without nullable() but still didn't work! Any help would be appreciated!

答:
try this ..

```<code>public function up()
{
    Schema::create('topic_video', function (Blueprint $table) {
        $table->integer('vendor_id')->unsigned()
    });
    Schema::table('topic_video', function($table) {
        $table->foreign('vendor_id')->references('id')->on('vendors');
    });
}
</code>```

and make sure the vendors migration create is before the topic_video migration create

Body:
I'm using Laravel 5.3 and I'm trying to create  FK, however when I migrate my table using artisan I'm getting the following error:

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `topic_video` add constraint `topic_video_vendor_id_foreign` foreign key (`vendor_id`) references `vendors` (`id`))

  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

I have tried multiple solutions on SOF for different laravel versions but none of them work.

This is my topic_video table (InnoDB)

This is an old and big project, as I don't have migrations for it, only for new tables we have migrations. So I have created a vendors (MyISAM)

Schema::create('vendors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('channel_url');
            $table->timestamps();
        });

Then I have add FK of above migration to topic_video table.

Schema::table('topic_video', function (Blueprint $table) {
            $table->integer('vendor_id')->unsigned()->nullable();
            $table->foreign('vendor_id')->references('id')->on('vendors');
        });

I have tried without unsigned(), without nullable() but still didn't work! Any help would be appreciated!

Body:
try this ..

public function up()
{
    Schema::create('topic_video', function (Blueprint $table) {
        $table->integer('vendor_id')->unsigned()
    });
    Schema::table('topic_video', function($table) {
        $table->foreign('vendor_id')->references('id')->on('vendors');
    });
}

and make sure the vendors migration create is before the topic_video migration create


问:
VB6 Using Set keyword producing empty object
I want to pass an object to a class and have that object retain all references, then need to pass that object over to a Form. Trying my code produces run-time error 438, "Object doesn't support this property or method".

I don't know what I'm doing wrong, but I need to pass an object reference to a different form and be able to pull the values from it.

```<code>Private TestObj As New Test
Private ScanObj As New Scan

Private Sub cmdLogin_Click()
  Set TestObj.ScanObj = ScanObj    'ScanObj is the object that holds my scan data
  Set frmScreen.TestObj = TestObj  'Set the TestObj to another Form that needs to use these vals
  frmScreen.Test                   'Expecting to see a MsgBox with one of the set object vals, but get nothing back. Why?
  frmScreen.Show
End Sub
</code>```

Does my expectation of how this should work, actually work this way?

EDIT:

I've simplified it.

My first form (Login) where I am gathering all my data:

```<code>Private TestObj As New Test
Private ScanObj As New Scan

Private Sub cmdLogin_Click()
  Set TestObj.ScanObj = ScanObj    'ScanObj is the object that holds my scan data
  Set frmScreen.TestObj = TestObj  'Set the TestObj in my Test class

  TestObj.Test                     'Call the Test class Test routine that should show one of my values, but instead get runtime 438

  frmScreen.Show
  Unload Me
End Sub
</code>```

Then the code from the Test class:

```<code>Public ScanObj As Object

Public Sub Test()
  MsgBox ScanObj.Get_P
End Sub
</code>```

答:
Going back to the original sample code, here is how I set it up:

Login Form

```<code>Option Explicit

Private TestObj As Test
Private ScanObj As Scan

Private Sub Form_Initialize()
  Set TestObj = New Test
  Set ScanObj = New Scan
End Sub

Private Sub cmdLogin_Click()
  Set TestObj.ScanObj = ScanObj
  Set frmScreen.TestObj = TestObj
  frmScreen.Test
  frmScreen.Show
End Sub
</code>```

Screen Form

```<code>Option Explicit

Public TestObj As Test

Public Sub Test()
   MsgBox "Test Name is: " & TestObj.Name
   MsgBox "Scanner Name is: " & TestObj.ScanObj.Get_P
End Sub
</code>```

Test Class

```<code>Option Explicit

Public ScanObj As Scan
Public Name As String

Private Sub Class_Initialize()
   Name = "Some Name"
End Sub
</code>```

Scan Class

```<code>Option Explicit

Public Function Get_P() As String
   Get_P = "Some String"
End Function
</code>```

Body:
I want to pass an object to a class and have that object retain all references, then need to pass that object over to a Form. Trying my code produces run-time error 438, "Object doesn't support this property or method".

I don't know what I'm doing wrong, but I need to pass an object reference to a different form and be able to pull the values from it.

Private TestObj As New Test
Private ScanObj As New Scan

Private Sub cmdLogin_Click()
  Set TestObj.ScanObj = ScanObj    'ScanObj is the object that holds my scan data
  Set frmScreen.TestObj = TestObj  'Set the TestObj to another Form that needs to use these vals
  frmScreen.Test                   'Expecting to see a MsgBox with one of the set object vals, but get nothing back. Why?
  frmScreen.Show
End Sub

Does my expectation of how this should work, actually work this way?

EDIT:

I've simplified it.

My first form (Login) where I am gathering all my data:

Private TestObj As New Test
Private ScanObj As New Scan

Private Sub cmdLogin_Click()
  Set TestObj.ScanObj = ScanObj    'ScanObj is the object that holds my scan data
  Set frmScreen.TestObj = TestObj  'Set the TestObj in my Test class

  TestObj.Test                     'Call the Test class Test routine that should show one of my values, but instead get runtime 438

  frmScreen.Show
  Unload Me
End Sub

Then the code from the Test class:

Public ScanObj As Object

Public Sub Test()
  MsgBox ScanObj.Get_P
End Sub

Body:
Going back to the original sample code, here is how I set it up:

Login Form

Option Explicit

Private TestObj As Test
Private ScanObj As Scan

Private Sub Form_Initialize()
  Set TestObj = New Test
  Set ScanObj = New Scan
End Sub

Private Sub cmdLogin_Click()
  Set TestObj.ScanObj = ScanObj
  Set frmScreen.TestObj = TestObj
  frmScreen.Test
  frmScreen.Show
End Sub

Screen Form

Option Explicit

Public TestObj As Test

Public Sub Test()
   MsgBox "Test Name is: " & TestObj.Name
   MsgBox "Scanner Name is: " & TestObj.ScanObj.Get_P
End Sub

Test Class

Option Explicit

Public ScanObj As Scan
Public Name As String

Private Sub Class_Initialize()
   Name = "Some Name"
End Sub

Scan Class

Option Explicit

Public Function Get_P() As String
   Get_P = "Some String"
End Function


问:
Eliminate dependency on MinGW-specific DLLs when compiling dynamic library
I am using msys2 to compile a library that uses autotools as the build system. The end result is a DLL. This DLL ends up referring to the following other DLLs that come with msys2:

libgcc_s_seh-1.dll

libstdc++-6.dll

libwinpthread-1.dll

How can I link these statically and eliminate these dependencies?

There are other questions dealing with this (example) and the solutions suggest using the options -static-libgcc -static-libstdc++. These work when linking an .exe, but they do not seem to work when linking a .dll.

I set the following variables before running ./configure (and checked the output to verify that these compiler options are really being used), but Dependency Walker still shows a dependency on libstdc++-6.dll, just as before.

```<code>export CFLAGS="-static-libgcc -static-libstdc++" CXXFLAGS="-static-libgcc -static-libstdc++" LDFLAGS="-static-libgcc -static-libstdc++"
</code>```

(I assume these must only go in LDFLAGS, but since I don't have a full understanding, I also added them in CFLAGS and CXXFLAGS.)

Is there a way to get rid of these dependencies when linking a DLL, not an EXE?

The library is written in a mix of C and C++ and has a C API.

答: Try just using the -static option in LDFLAGs.  I tested it just now in MSYS2 and it worked for me.

Body:
I am using msys2 to compile a library that uses autotools as the build system. The end result is a DLL. This DLL ends up referring to the following other DLLs that come with msys2:

libgcc_s_seh-1.dll

libstdc++-6.dll

libwinpthread-1.dll

How can I link these statically and eliminate these dependencies?

There are other questions dealing with this (example) and the solutions suggest using the options -static-libgcc -static-libstdc++. These work when linking an .exe, but they do not seem to work when linking a .dll.

I set the following variables before running ./configure (and checked the output to verify that these compiler options are really being used), but Dependency Walker still shows a dependency on libstdc++-6.dll, just as before.

export CFLAGS="-static-libgcc -static-libstdc++" CXXFLAGS="-static-libgcc -static-libstdc++" LDFLAGS="-static-libgcc -static-libstdc++"

(I assume these must only go in LDFLAGS, but since I don't have a full understanding, I also added them in CFLAGS and CXXFLAGS.)

Is there a way to get rid of these dependencies when linking a DLL, not an EXE?

The library is written in a mix of C and C++ and has a C API.


问:
Azure Equivalent of Resource Group Local Host
I've had a little dig through azure documentation but couldn't find a definitive answer.

I have an app service and an azure db sitting in the same resource group, and I am finding the site takes a long time to connect and get responses back from the database only in the hosted environment.

Is it possible to specify a localhost equivalent as they are in the same resource group, and would this make things any quicker?

答:
Resource Group does not have any impact on the connectivity or latency of the application and the database. It is just to group the Azure resources together based on a Project/Envrionment.

There is no equivalent for resourcegroup or even appservice unless if you want to run your application in IIS or any other server.

If you really want to see what is causing the connectivity issue, i will recommend you to monitor the request and response using Azure Monitor.

I think you need to understand the cloud concepts first before trying out anything.


问:
How to remove white spaces before each value from array list in the java code below
```<code>test_map = new HashMap();
json_test_data = slurper.parseText(test_data.toString());
test_map=json_test_data.row;
code_list = test_map.getAt("code").toString();
</code>```

Output:

```<code>code_list: [
    QU95QE007, IP2H1N001, Q37VS001, Q2908003,
    Q2C94001, 2FZ3001, 94DM002, 193R005,
    2FZ3001,  94DM002,  193R005,  94DM002
]
</code>```

答: Well... Since a String is an array of characters. Try to change the first element of the string to an empty char like this "" cause before it was this " "</p>

Body:
test_map = new HashMap();
json_test_data = slurper.parseText(test_data.toString());
test_map=json_test_data.row;
code_list = test_map.getAt("code").toString();

Output:

code_list: [
    QU95QE007, IP2H1N001, Q37VS001, Q2908003,
    Q2C94001, 2FZ3001, 94DM002, 193R005,
    2FZ3001,  94DM002,  193R005,  94DM002
]


问:
Input label not at center of select dropdown box
I am not able to center my text in the middle of the select dropdown for some reason.
Implementation status field in image

Here is my code

```<code>  <FormControl style={{ width: "80%" }} size="small">
        <InputLabel
          htmlFor="Implementation Status"
          style={{ marginLeft: 10 }}
          margin="dense"
        >
          Implementation Status
        </InputLabel>
        <Select
          labelId="Implementation Status"
          name="name"
          onChange={handleChange("Status")}
          defaultValue={values.Status}
          variant="outlined"
          inputProps={{
            id: "Implementation Status",
            name: "age"
          }}
          >
          <MenuItem value="Implemented">Implemented</MenuItem>
          <MenuItem value="Implementation in Progress">
            Implementation in Progress
          </MenuItem>
          <MenuItem value="Not Implemented">Not Implemented</MenuItem>
        </Select>
      </FormControl>
</code>```

答:
try doing this

```<code>style={{ marginLeft: 20, marginTop: -10 }}
</code>```

in the InputLabel
will make

Body:
I am not able to center my text in the middle of the select dropdown for some reason.
Implementation status field in image

Here is my code

  <FormControl style={{ width: "80%" }} size="small">
        <InputLabel
          htmlFor="Implementation Status"
          style={{ marginLeft: 10 }}
          margin="dense"
        >
          Implementation Status
        </InputLabel>
        <Select
          labelId="Implementation Status"
          name="name"
          onChange={handleChange("Status")}
          defaultValue={values.Status}
          variant="outlined"
          inputProps={{
            id: "Implementation Status",
            name: "age"
          }}
          >
          <MenuItem value="Implemented">Implemented</MenuItem>
          <MenuItem value="Implementation in Progress">
            Implementation in Progress
          </MenuItem>
          <MenuItem value="Not Implemented">Not Implemented</MenuItem>
        </Select>
      </FormControl>

Body:
try doing this

style={{ marginLeft: 20, marginTop: -10 }}

in the InputLabel
will make


问:
How to get last inserted all records in mysql
Actually I don't know how to get last inserted records in two table.

I want to get last recently inserted all records in table.

I used LAST_INSERT_ID() function but it gives only one last record and i want multiple records in table.

答:
I'm looking into this myself right now and the only way I can come up with is to retrieve the number of affected rows from the most recent query, and then select that many  rows from the table, with the selection ordered by ID (or whatever is most appropriate to your use case) in Descending order, thus:

The insertion query:

```<code>INSERT INTO db.table (id,var1,var2)
VALUES
  (NULL,'value1','value2')
  (NULL,'value3','value4')
  (NULL,'value5','value6')
</code>```

Use mysql_affected_rows() to retrieve how many rows were inserted.

(In PHP this would be $number = $mysqli_object->affected_rows - your code implementation may differ)

then fetch the rows using that value as the LIMIT value:

```<code>SELECT * FROM db.table ORDER BY id DESC LIMIT $number
</code>```

Ideally you'd wrap that up in a method or function dependant on your coding and use case.

Body:
I'm looking into this myself right now and the only way I can come up with is to retrieve the number of affected rows from the most recent query, and then select that many  rows from the table, with the selection ordered by ID (or whatever is most appropriate to your use case) in Descending order, thus:

The insertion query:

INSERT INTO db.table (id,var1,var2)
VALUES
  (NULL,'value1','value2')
  (NULL,'value3','value4')
  (NULL,'value5','value6')

Use mysql_affected_rows() to retrieve how many rows were inserted.

(In PHP this would be $number = $mysqli_object->affected_rows - your code implementation may differ)

then fetch the rows using that value as the LIMIT value:

SELECT * FROM db.table ORDER BY id DESC LIMIT $number

Ideally you'd wrap that up in a method or function dependant on your coding and use case.


问:
How to definitively align vertically and centrally with the bootstrap?
I tried a lot before creating this doubt, but I didn't find anything like that, I can't align a div vertically with the bootstrap, how can I do this?

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

Nome

Dev

  PORTFÓLIO

```

答:
It is not elegant, but will work.

СSS:

```<code>.container{
  width: 50%;
  height: 100%;
  overflow: hidden;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}
</code>```

Body:
It is not elegant, but will work.

СSS:

.container{
  width: 50%;
  height: 100%;
  overflow: hidden;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}


问:
Has many through, self related, and polymorphic for STI models saving STI parent class name instead of STI child class name
guys we are building a sort of address book, we have Users, Contacts and a parent Table called UserEntity. We want to relate them in a many-to-many association through a table called Relationship, this relations have to be in a self related in UserEntity table.

One User has many Contacts and one Contact has many Users.

Later on we need relate new models with Users so the Relationship model must be polymorphic. We already built this:

```<code>class UserEntity < ActiveRecord::Base
  self.table_name = "users"
end

class User < UserEntity
  has_many :relationships, as: :relatable
  has_many :contacts, through: :relationships, source: :relatable, source_type "Contact"
end

class Contact < UserEntity
  has_many :relationships, as: :relatable
  has_many :users, through: :relationships, source: :relatable, source_type "User"
end

class Relationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :relatable, polymorphic: true
end
</code>```

but when we try to save the association user.contacts << contact the relatable_type field saves "UserEntity" value and not "Contact" or "User" value. We already tried to do this without any favorable results http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations

How can we make that relatable_type value saves the model name ("Contact" || "User") and not the STI parent model name ("UserEntity")?

答:
You must set UserEntity as abstract class:

```<code>class UserEntity < ActiveRecord::Base
  self.table_name = "users"
  self.abstract_class = true
end
</code>```

Then value relatable_type can be User or Contact.

By default RoR save in relatable_type value of base_class method in your case:

```<code>class UserEntity < ActiveRecord::Base
end

class User < UserEntity
end

class Contact < UserEntity
end

irb(main):010:0> User.base_class.name
=> "UserEntity"

irb(main):011:0> Contact.base_class.name
=> "UserEntity"
</code>```

When you make UserEntity as abstract class:

```<code>class UserEntity < ActiveRecord::Base
  self.abstract_class = true
end

class User < UserEntity
end

class Contact < UserEntity
end

irb(main):010:0> User.base_class.name
=> "User"

irb(main):011:0> Contact.base_class.name
=> "Contact"
</code>```

Here defined method which store class name (https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb#L14):

```<code>def replace_keys(record)
  super
  owner[reflection.foreign_type] = record ? record.class.polymorphic_name : nil
end
</code>```

```<code>def polymorphic_name
  base_class.name
end
</code>```

Body:
guys we are building a sort of address book, we have Users, Contacts and a parent Table called UserEntity. We want to relate them in a many-to-many association through a table called Relationship, this relations have to be in a self related in UserEntity table.

One User has many Contacts and one Contact has many Users.

Later on we need relate new models with Users so the Relationship model must be polymorphic. We already built this:

class UserEntity < ActiveRecord::Base
  self.table_name = "users"
end

class User < UserEntity
  has_many :relationships, as: :relatable
  has_many :contacts, through: :relationships, source: :relatable, source_type "Contact"
end

class Contact < UserEntity
  has_many :relationships, as: :relatable
  has_many :users, through: :relationships, source: :relatable, source_type "User"
end

class Relationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :relatable, polymorphic: true
end

but when we try to save the association user.contacts << contact the relatable_type field saves "UserEntity" value and not "Contact" or "User" value. We already tried to do this without any favorable results http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations

How can we make that relatable_type value saves the model name ("Contact" || "User") and not the STI parent model name ("UserEntity")?

Body:
You must set UserEntity as abstract class:

class UserEntity < ActiveRecord::Base
  self.table_name = "users"
  self.abstract_class = true
end

Then value relatable_type can be User or Contact.

By default RoR save in relatable_type value of base_class method in your case:

class UserEntity < ActiveRecord::Base
end

class User < UserEntity
end

class Contact < UserEntity
end

irb(main):010:0> User.base_class.name
=> "UserEntity"

irb(main):011:0> Contact.base_class.name
=> "UserEntity"

When you make UserEntity as abstract class:

class UserEntity < ActiveRecord::Base
  self.abstract_class = true
end

class User < UserEntity
end

class Contact < UserEntity
end

irb(main):010:0> User.base_class.name
=> "User"

irb(main):011:0> Contact.base_class.name
=> "Contact"

Here defined method which store class name (https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb#L14):

def replace_keys(record)
  super
  owner[reflection.foreign_type] = record ? record.class.polymorphic_name : nil
end

def polymorphic_name
  base_class.name
end


问:
filter for rows with n largest values for each group

Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')
```

```| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |
```

<h3>Desired Output</h3>

<pre class="lang-py prettyprint-override"><code>df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output
</code>```

```<code>| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |
</code>```

答:
You can use df.groupby.rank method:

```<code>In [1401]: df[df.groupby('team')['points'].rank(ascending=False) <= 3]
Out[1401]:
   team   player  points
0     A    Alice      15
1     A    Becky      11
2     A   Carmen      13
5     B     Fran      28
6     B    Greta      29
8     B     Iris      25
11    C     Lucy      23
12    C    Molly      18
14    C  Ophelia      15
</code>```

Body:
Context

I want, for each team, the rows of the data frame that contains the top three scoring players.

In my head, it is a combination of Dataframe.nlargest() and Dataframe.groupby() but I don't think this is supported.
My ideal solution is:

performed directly on df without having to create other dataframes

legible, and

relatively performant (real df shape is 7M rows and 5 col)

Input

import pandas as pd
df = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"A","4":"A","5":"B","6":"B","7":"B","8":"B","9":"B","10":"C","11":"C","12":"C","13":"C","14":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Donna","4":"Elizabeth","5":"Fran","6":"Greta","7":"Heather","8":"Iris","9":"Jackie","10":"Kelly","11":"Lucy","12":"Molly","13":"Nina","14":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":8,"4":10,"5":28,"6":29,"7":18,"8":25,"9":9,"10":12,"11":23,"12":18,"13":10,"14":15}}')

| team | player    | points |
|------|-----------|--------|
| A    | Alice     | 15     |
| A    | Becky     | 11     |
| A    | Carmen    | 13     |
| A    | Donna     | 8      |
| A    | Elizabeth | 10     |
| B    | Fran      | 28     |
| B    | Greta     | 29     |
| B    | Heather   | 18     |
| B    | Iris      | 25     |
| B    | Jackie    | 9      |
| C    | Kelly     | 12     |
| C    | Lucy      | 23     |
| C    | Molly     | 18     |
| C    | Nina      | 10     |
| C    | Ophelia   | 15     |

Desired Output

df_output = pd.read_json('{"team":{"0":"A","1":"A","2":"A","3":"B","4":"B","5":"B","6":"C","7":"C","8":"C"},"player":{"0":"Alice","1":"Becky","2":"Carmen","3":"Fran","4":"Greta","5":"Iris","6":"Lucy","7":"Molly","8":"Ophelia"},"points":{"0":15,"1":11,"2":13,"3":28,"4":29,"5":25,"6":23,"7":18,"8":15}}')
df_output

| team | player  | points |
|------|---------|--------|
| A    | Alice   | 15     |
| A    | Becky   | 11     |
| A    | Carmen  | 13     |
| B    | Fran    | 28     |
| B    | Greta   | 29     |
| B    | Iris    | 25     |
| C    | Lucy    | 23     |
| C    | Molly   | 18     |
| C    | Ophelia | 15     |

Body:
You can use df.groupby.rank method:

In [1401]: df[df.groupby('team')['points'].rank(ascending=False) <= 3]
Out[1401]:
   team   player  points
0     A    Alice      15
1     A    Becky      11
2     A   Carmen      13
5     B     Fran      28
6     B    Greta      29
8     B     Iris      25
11    C     Lucy      23
12    C    Molly      18
14    C  Ophelia      15