问:
Adding (data dependent) color to arrows in d3.js network
I have colored lines in my d3.js network that depend on some attribute of the nodes that the line connects. I would like to add an arrow to my link that matches the color of the line instead of being the same color. This is the code I have for making the same colored arrows:

```<code>    var arrow = svg.append("svg:defs").selectAll("marker")
    .data(["end"])      // Different link/path types can be defined here
  .enter().append("svg:marker")    // This section adds in the arrows
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", radius/2)
    .attr("markerHeight", radius/2)
    .attr("orient", "auto")
  .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

  var link = svg.append("g")
      .attr("class", "links")
      .selectAll("line")
      .data(links)
      .enter().append("line")
      .attr("stroke-width", radius*.25)
      .attr("stroke",function(d){return color(node_color_map[d.source])})
      .attr("marker-end", "url(#end)")
      .attr("stroke",function(d){return color(node_color_map[d.source])})
      ;

</code>```

Any suggestion is appreciated. Thank you!

Body:
I have colored lines in my d3.js network that depend on some attribute of the nodes that the line connects. I would like to add an arrow to my link that matches the color of the line instead of being the same color. This is the code I have for making the same colored arrows:

    var arrow = svg.append("svg:defs").selectAll("marker")
    .data(["end"])      // Different link/path types can be defined here
  .enter().append("svg:marker")    // This section adds in the arrows
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", radius/2)
    .attr("markerHeight", radius/2)
    .attr("orient", "auto")
  .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

  var link = svg.append("g")
      .attr("class", "links")
      .selectAll("line")
      .data(links)
      .enter().append("line")
      .attr("stroke-width", radius*.25)
      .attr("stroke",function(d){return color(node_color_map[d.source])})
      .attr("marker-end", "url(#end)")
      .attr("stroke",function(d){return color(node_color_map[d.source])})
      ;

Any suggestion is appreciated. Thank you!


来源: stackexchange

问:
Function failed on loading user code. This is likely due to a bug in the user code
I am trying to deploy my firebase cloud functions, but it gives me an error message after the functions were uploaded. My colleague however, on his computer, can still deploy functions as per usual.

We are using the same git repository.
The only difference between me and him is that I am on a mac and he is on windows.
He tried it on another windows computer, where it is also working as expected.

The error message:

```<code>Function failed on loading user code. This is likely due to a bug in the user code.
Error message:
Error: please examine your function logs to see the error cause:
https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs.
Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging.
Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
</code>```

In the logs of the functions there isn't more information about the error, just the same message that I got in my terminal. Typescript compiles, the folder is being uploaded, and it tells me that the functions are being updated. In the final step (at least that's what it seems), something goes wrong. I cannot figure out what exactly the cause of the error is, because I cannot find more information in the function's logs. How is it even possible, that there are exceptions in firebase that don't tell you whats wrong?

We suspected a problem with the global scope, however, when my colleague deploys, it is working just fine with the same codebase so this shouldn't be the problem.

What I tried

reinstalling node_modules

logging in and out of firebase

using a different firebase account

exchanging package-lock.json with my colleague

rebooting vscode and mac

clearing npm cache

node 14, node 16, node 18

I am using the latest version of firebase-tools and also the latest versions of all firebase dependencies.

What else can I try?

The project is very important and the deadline is close.

I appreciate any help.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to deploy my firebase cloud functions, but it gives me an error message after the functions were uploaded. My colleague however, on his computer, can still deploy functions as per usual.

We are using the same git repository.
The only difference between me and him is that I am on a mac and he is on windows.
He tried it on another windows computer, where it is also working as expected.

The error message:

Function failed on loading user code. This is likely due to a bug in the user code.
Error message:
Error: please examine your function logs to see the error cause:
https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs.
Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging.
Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.

In the logs of the functions there isn't more information about the error, just the same message that I got in my terminal. Typescript compiles, the folder is being uploaded, and it tells me that the functions are being updated. In the final step (at least that's what it seems), something goes wrong. I cannot figure out what exactly the cause of the error is, because I cannot find more information in the function's logs. How is it even possible, that there are exceptions in firebase that don't tell you whats wrong?

We suspected a problem with the global scope, however, when my colleague deploys, it is working just fine with the same codebase so this shouldn't be the problem.

What I tried

reinstalling node_modules

logging in and out of firebase

using a different firebase account

exchanging package-lock.json with my colleague

rebooting vscode and mac

clearing npm cache

node 14, node 16, node 18

I am using the latest version of firebase-tools and also the latest versions of all firebase dependencies.

What else can I try?

The project is very important and the deadline is close.

I appreciate any help.


问:
Javascript / Typescript - How to remove duplicates from the code
I have a piece of code that basically repeats itself. The only difference is the type of params and scan invokes this.getDbClient().scan(params) and query invokes this.getDbClient().query(params).

```<code>static scanTable = async (params: DynamoDB.DocumentClient.ScanInput) => {
    let items;
    let scanResults: any[] = [];
    do {
        items = await this.getDbClient().scan(params).promise();
        (items.Items || []).forEach((item) => scanResults.push(item));
        params.ExclusiveStartKey = items.LastEvaluatedKey;
    } while (typeof items.LastEvaluatedKey !== 'undefined');

    return scanResults;
}

static queryTable = async (params: DynamoDB.DocumentClient.QueryInput) => {
    let items;
    let scanResults: any[] = [];
    do {
        items = await this.getDbClient().query(params).promise();
        (items.Items || []).forEach((item) => scanResults.push(item));
        params.ExclusiveStartKey = items.LastEvaluatedKey;
    } while (typeof items.LastEvaluatedKey !== 'undefined');

    return scanResults;
}
</code>```

I tried to extract the function and use

```<code>async (params: DynamoDB.DocumentClient.ScanInput | DynamoDB.DocumentClient.QueryInput)
</code>```

and then trying to do

```<code>if params instanceof DynamoDB.DocumentClient.ScanInput call `scan(params)`
else if params instanceof DynamoDB.DocumentClient.QueryInput call `query(params)`
</code>```

but it seems that instanceof cannot be used

ERROR: Property 'ScanInput' does not exist on type 'typeof
DocumentClient'.ts(2339)

ERROR: Property 'QueryInput' does not exist on type 'typeof
DocumentClient'.ts(2339)

What can I do here to avoid the duplication of the code?
Any idea?

Body:
I have a piece of code that basically repeats itself. The only difference is the type of params and scan invokes this.getDbClient().scan(params) and query invokes this.getDbClient().query(params).

static scanTable = async (params: DynamoDB.DocumentClient.ScanInput) => {
    let items;
    let scanResults: any[] = [];
    do {
        items = await this.getDbClient().scan(params).promise();
        (items.Items || []).forEach((item) => scanResults.push(item));
        params.ExclusiveStartKey = items.LastEvaluatedKey;
    } while (typeof items.LastEvaluatedKey !== 'undefined');

    return scanResults;
}

static queryTable = async (params: DynamoDB.DocumentClient.QueryInput) => {
    let items;
    let scanResults: any[] = [];
    do {
        items = await this.getDbClient().query(params).promise();
        (items.Items || []).forEach((item) => scanResults.push(item));
        params.ExclusiveStartKey = items.LastEvaluatedKey;
    } while (typeof items.LastEvaluatedKey !== 'undefined');

    return scanResults;
}

I tried to extract the function and use

async (params: DynamoDB.DocumentClient.ScanInput | DynamoDB.DocumentClient.QueryInput)

and then trying to do

if params instanceof DynamoDB.DocumentClient.ScanInput call `scan(params)`
else if params instanceof DynamoDB.DocumentClient.QueryInput call `query(params)`

but it seems that instanceof cannot be used

ERROR: Property 'ScanInput' does not exist on type 'typeof
DocumentClient'.ts(2339)

ERROR: Property 'QueryInput' does not exist on type 'typeof
DocumentClient'.ts(2339)

What can I do here to avoid the duplication of the code?
Any idea?


问:
Transforming the return from API in a CSV table
I'm trying to make a method that get all data from the request and transforming in a CSV table.

My method look like this:

```<code>todasGuias() {
this.pagina = 1;
this.paginaBusca = this.pagina;
while (this.paginaBusca <= this.listaGuias.TotalPages) {
  this.homeService
    .getGuias( this.ano, this.mes, this.paginaBusca)
    .subscribe((data) => {
      this.listaGuias = data.Dados[0];
      console.log(this.listaGuias.ResultList);
    });
  this.paginaBusca++;
}

var options = {
  fieldSeparator: ',',
  quoteStrings: '"',
  decimalseparator: '.',
  showLabels: true,
  showTitle: true,
  title: 'Consulta',
  useBom: true,
  headers: [ 'Guia', 'Tipo', 'Guia Do Contratado', 'Protocolo', 'Valor Informado', 'Valor Total', 'Cliente'],
};

new ngxCsv(this.listaGuias.ResultList, 'Consulta', options);
</code>```

My service look like this:

```<code>public getGuias( ano: any, mes: any, pagina:any): Observable<any> {
const token = this.token.retornaToken();
const headers = new HttpHeaders({ Authorization: `Bearer ${token}` });

return this.http.get(`API/TpoRelatorio=1
&Ano=${ano}
&Mes=${mes}
&Page=${pagina}
&Count=0`,{ headers }
)
</code>```

}

Body:
I'm trying to make a method that get all data from the request and transforming in a CSV table.

My method look like this:

todasGuias() {
this.pagina = 1;
this.paginaBusca = this.pagina;
while (this.paginaBusca <= this.listaGuias.TotalPages) {
  this.homeService
    .getGuias( this.ano, this.mes, this.paginaBusca)
    .subscribe((data) => {
      this.listaGuias = data.Dados[0];
      console.log(this.listaGuias.ResultList);
    });
  this.paginaBusca++;
}

var options = {
  fieldSeparator: ',',
  quoteStrings: '"',
  decimalseparator: '.',
  showLabels: true,
  showTitle: true,
  title: 'Consulta',
  useBom: true,
  headers: [ 'Guia', 'Tipo', 'Guia Do Contratado', 'Protocolo', 'Valor Informado', 'Valor Total', 'Cliente'],
};

new ngxCsv(this.listaGuias.ResultList, 'Consulta', options);

My service look like this:

public getGuias( ano: any, mes: any, pagina:any): Observable<any> {
const token = this.token.retornaToken();
const headers = new HttpHeaders({ Authorization: `Bearer ${token}` });

return this.http.get(`API/TpoRelatorio=1
&Ano=${ano}
&Mes=${mes}
&Page=${pagina}
&Count=0`,{ headers }
)

}


问:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure On Jenkins
I am trying to automate a web application and this web application needs to get some information from the database.
the database is not local but in AWS , and I checked the URL and port.
After login , it needs to get a certain link from the database to open it and keep going.
In my local it works perfectly but once I deployed on Jenkins I found this error.

this is the error :

```<code>com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:829)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:449)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:242)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at com.bmw.automation.pages.abstraction.AbstractPageBmw.getLastLinkQRCode(AbstractPageBmw.java:115)
    at com.bmw.automation.pages.common.GmailBoxPage.openLinkQRcode(GmailBoxPage.java:575)
    at com.bmw.automation.bdd.stepsDefinition.GmailBoxPageStepsDefinition.i_extract_the_link(GmailBoxPageStepsDefinition.java:228)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at io.cucumber.java.Invoker.doInvoke(Invoker.java:66)
    at io.cucumber.java.Invoker.invoke(Invoker.java:24)
    at io.cucumber.java.AbstractGlueDefinition.invokeMethod(AbstractGlueDefinition.java:47)
    at io.cucumber.java.JavaStepDefinition.execute(JavaStepDefinition.java:29)
    at io.cucumber.core.runner.CoreStepDefinition.execute(CoreStepDefinition.java:66)
    at io.cucumber.core.runner.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:63)
    at io.cucumber.core.runner.ExecutionMode$1.execute(ExecutionMode.java:10)
    at io.cucumber.core.runner.TestStep.executeStep(TestStep.java:92)
    at io.cucumber.core.runner.TestStep.run(TestStep.java:64)
    at io.cucumber.core.runner.PickleStepTestStep.run(PickleStepTestStep.java:51)
    at io.cucumber.core.runner.TestCase.run(TestCase.java:104)
    at io.cucumber.core.runner.Runner.runPickle(Runner.java:71)
    at io.cucumber.testng.TestNGCucumberRunner.lambda$runScenario$0(TestNGCucumberRunner.java:116)
    at io.cucumber.core.runtime.CucumberExecutionContext.runTestCase(CucumberExecutionContext.java:117)
    at io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:113)
    at io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
    at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
    at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
    at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
    at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.testng.TestRunner.privateRun(TestRunner.java:794)
    at org.testng.TestRunner.run(TestRunner.java:596)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
    at org.testng.SuiteRunner.run(SuiteRunner.java:276)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
    at org.testng.TestNG.runSuites(TestNG.java:1063)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:62)
    at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:141)
    at org.apache.maven.surefire.Surefire.run(Surefire.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
    at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:89)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:120)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:949)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:819)
    ... 62 more
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
    at java.net.Socket.connect(Socket.java:606)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:156)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63)
    ... 65 more

</code>```

And this is my code :

```<code>    public String getLastLinkQRCode() {
        String lastLinkQrCode = "";
        Connection myConnection = null;
        try {
            if(PropertiesReader.getEnvironementName().equalsIgnoreCase("test")) {
                myConnection = DriverManager.getConnection(PropertiesReader.getBmwTestDatabaseUrl_PPV(), PropertiesReader.getBmwTestDatabaseLogin_PPV(), PropertiesReader.getBmwTestDatabasePassword_PPV());
            } else {
                myConnection = DriverManager.getConnection(PropertiesReader.getBmwProdDatabaseUrl(), PropertiesReader.getBmwProdDatabaseLogin(), PropertiesReader.getBmwProdDatabasePassword());
                }
            Statement myStatement = myConnection.createStatement();
            ResultSet myResult = myStatement.executeQueriy("select link from t1 where mail ='x1x1x1x1@gmail.com' ORDER BY send_date DESC LIMIT 1");
            while(myResult.next()) {
                lastLink= myResult.getString("link");
            }
            myConnection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(lastLinkQrCode);
        return lastLink;
    }
}
</code>```

Body:
I am trying to automate a web application and this web application needs to get some information from the database.
the database is not local but in AWS , and I checked the URL and port.
After login , it needs to get a certain link from the database to open it and keep going.
In my local it works perfectly but once I deployed on Jenkins I found this error.

this is the error :

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:829)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:449)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:242)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at com.bmw.automation.pages.abstraction.AbstractPageBmw.getLastLinkQRCode(AbstractPageBmw.java:115)
    at com.bmw.automation.pages.common.GmailBoxPage.openLinkQRcode(GmailBoxPage.java:575)
    at com.bmw.automation.bdd.stepsDefinition.GmailBoxPageStepsDefinition.i_extract_the_link(GmailBoxPageStepsDefinition.java:228)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at io.cucumber.java.Invoker.doInvoke(Invoker.java:66)
    at io.cucumber.java.Invoker.invoke(Invoker.java:24)
    at io.cucumber.java.AbstractGlueDefinition.invokeMethod(AbstractGlueDefinition.java:47)
    at io.cucumber.java.JavaStepDefinition.execute(JavaStepDefinition.java:29)
    at io.cucumber.core.runner.CoreStepDefinition.execute(CoreStepDefinition.java:66)
    at io.cucumber.core.runner.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:63)
    at io.cucumber.core.runner.ExecutionMode$1.execute(ExecutionMode.java:10)
    at io.cucumber.core.runner.TestStep.executeStep(TestStep.java:92)
    at io.cucumber.core.runner.TestStep.run(TestStep.java:64)
    at io.cucumber.core.runner.PickleStepTestStep.run(PickleStepTestStep.java:51)
    at io.cucumber.core.runner.TestCase.run(TestCase.java:104)
    at io.cucumber.core.runner.Runner.runPickle(Runner.java:71)
    at io.cucumber.testng.TestNGCucumberRunner.lambda$runScenario$0(TestNGCucumberRunner.java:116)
    at io.cucumber.core.runtime.CucumberExecutionContext.runTestCase(CucumberExecutionContext.java:117)
    at io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:113)
    at io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
    at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
    at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
    at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
    at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.testng.TestRunner.privateRun(TestRunner.java:794)
    at org.testng.TestRunner.run(TestRunner.java:596)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
    at org.testng.SuiteRunner.run(SuiteRunner.java:276)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
    at org.testng.TestNG.runSuites(TestNG.java:1063)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:62)
    at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:141)
    at org.apache.maven.surefire.Surefire.run(Surefire.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
    at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:89)
    at com.mysql.cj.NativeSession.connect(NativeSession.java:120)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:949)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:819)
    ... 62 more
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
    at java.net.Socket.connect(Socket.java:606)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:156)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63)
    ... 65 more

And this is my code :

    public String getLastLinkQRCode() {
        String lastLinkQrCode = "";
        Connection myConnection = null;
        try {
            if(PropertiesReader.getEnvironementName().equalsIgnoreCase("test")) {
                myConnection = DriverManager.getConnection(PropertiesReader.getBmwTestDatabaseUrl_PPV(), PropertiesReader.getBmwTestDatabaseLogin_PPV(), PropertiesReader.getBmwTestDatabasePassword_PPV());
            } else {
                myConnection = DriverManager.getConnection(PropertiesReader.getBmwProdDatabaseUrl(), PropertiesReader.getBmwProdDatabaseLogin(), PropertiesReader.getBmwProdDatabasePassword());
                }
            Statement myStatement = myConnection.createStatement();
            ResultSet myResult = myStatement.executeQueriy("select link from t1 where mail ='x1x1x1x1@gmail.com' ORDER BY send_date DESC LIMIT 1");
            while(myResult.next()) {
                lastLink= myResult.getString("link");
            }
            myConnection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(lastLinkQrCode);
        return lastLink;
    }
}


问:
How to show a picture with .hbs file?
I have a .hbs page and i want to show a picture in a directory, but i try some code but is not working properly, maybe someone outside can give me a answer.

So i do this code:

```<code>  {{#each PhotosFiles}}
  {{this.PathFilename}}
  <img style="display:block; width:200px;height:200px;" id="" src="{{this.PathFilename}}"/>
  <img src="/files/oncargophotos/2022/12/19/354542_0_11659_C.jpg"/>
  {{/each}}
</code>```

and on my webiste appears like that:.

what I have done wrong in my code ?

I already try it other things on my,

```<code>{{#each PhotosFiles}}
  {{this.PathFilename}}
</code>```

but i still in the same error

Title: How to show a picture with .hbs file?

Body:
I have a .hbs page and i want to show a picture in a directory, but i try some code but is not working properly, maybe someone outside can give me a answer.

So i do this code:

  {{#each PhotosFiles}}
  {{this.PathFilename}}

  {{/each}}

and on my webiste appears like that:.

what I have done wrong in my code ?

I already try it other things on my,

{{#each PhotosFiles}}
  {{this.PathFilename}}

but i still in the same error


问:
AWS Managed Apache Airflow Dags Log Search
AWS Managed Apache Airflow Dags Log Search, Airflow jobs runs as step in EMR cluster.
We are facing issue in looking the failed Dags log. Output shows only S3 folder.

EMR job failed for reason Unknown Error. with message None and log file s3://test-bucket-logs/j-HNKNG13GHYTD/steps/s-UYHJGTHEFGER/ INFO marking task as FAILED. dag_id=test_tag, taks_id=test

We have to go to steps/s- folder then fetch the application log ID then again go to container folder to see the logs.

Is there any solution for this??/


问:
vite-nuxt error when added to Nuxt 2 project
I'm working on a Nuxt 2 project and I want to use vite instead of webpack.

I installed nuxt-vite and added it to buildModules and it worked but I got an error regarding JSX in some component:

```<code>[ERROR] The JSX syntax extension is not currently enabled

  <div
  ^

The esbuild loader for this file is currently set to "js" but it must be set to "jsx"
to be able to parse JSX syntax. You can use "loader: { '.js': 'jsx' }" to do that.
</code>```

I installed @vitejs/plugin-vue-jsx and added it to vite withing nuxt.config:

vite: {
  plugins: [vueJsx({})]
}
```
<p>Now I get a different error that I don't know how to solve</p>
```TypeError: vite.createFilter is not a function
```
<p>These are the packages (only what I think is relevant to the question, I'll provide full list if needed)</p>
<pre class="lang-json prettyprint-override"><code>"devDependencies": {
  "@vitejs/plugin-vue-jsx": "^3.0.0",
  "nuxt-vite": "^0.3.5",
  "nuxt": "^2.15.3",
}
</code>```

Body:
I'm working on a Nuxt 2 project and I want to use vite instead of webpack.

I installed nuxt-vite and added it to buildModules and it worked but I got an error regarding JSX in some component:

[ERROR] The JSX syntax extension is not currently enabled

  <div
  ^

The esbuild loader for this file is currently set to "js" but it must be set to "jsx"
to be able to parse JSX syntax. You can use "loader: { '.js': 'jsx' }" to do that.

I installed @vitejs/plugin-vue-jsx and added it to vite withing nuxt.config:

vite: {
  plugins: [vueJsx({})]
}

Now I get a different error that I don't know how to solve

TypeError: vite.createFilter is not a function

These are the packages (only what I think is relevant to the question, I'll provide full list if needed)

"devDependencies": {
  "@vitejs/plugin-vue-jsx": "^3.0.0",
  "nuxt-vite": "^0.3.5",
  "nuxt": "^2.15.3",
}


问:
How to read csv with multi row-column data with Pandas
I have csv files with thousands of records intended for import somewhere else and the format they're in is only easy to look at but not reading for importing. Here is a sample of the record structure:

These files have a single record with columns in multiple rows below them. As you can imagine, this is a bit tricky to read as one would expect one header for all records.

My question is, is this possible to read with pandas's pandas.read_csv?

I've tried Reading this documentation on parameters we can pass to read_csv but I can't see one that I can make use of.

if Pandas doesn't work for this kind of format, what would you recommend?


问:
does ktor support multiple sslConnector config for individual domain along with specific ssl certificate
I want to use Ktor to serve two domains, with individual ssl certificate, below is my configuration to do :

val environment = applicationEngineEnvironment {
    val pwdCharArray = "password1".toCharArray()
    val kstFile = File("perkey/site1.jks")
    val keyStore = KeyStore.getInstance("JKS").apply { load(kstFile.inputStream(), pwdCharArray) }
    sslConnector(
        keyStore = keyStore,
        keyAlias = "site1",
        keyStorePassword = { pwdCharArray },
        privateKeyPassword = { pwdCharArray }
    ) {
        host = "site1.domain.com"
        port = 3443
        keyStorePath = kstFile
    }

    val pwdCharArray2 = "site2".toCharArray()
    val kstFile2 = File("perkey/site2.jks")
    val keyStore2 = KeyStore.getInstance("JKS").apply { load(kstFile2.inputStream(), pwdCharArray2) }
    sslConnector(
        keyStore = keyStore2,
        keyAlias = "site2",
        keyStorePassword = { pwdCharArray2 },
        privateKeyPassword = { pwdCharArray2 }
    ) {
        host = "site2.domain.com"
        port = 443
        keyStorePath = kstFile2
    }

    module(Application::module)
}
embeddedServer(Tomcat, environment).start(wait = true)
```
<p>after <code>./gradlew run</code> I saw the log:</p>
```2022-12-19 22:46:28 INFO Responding at https://site1.domain.com:3443
2022-12-19 22:46:28 INFO Responding at https://site2.domain.com:443
```
<p>but I can only visit the site2.domain.com that used the default port of ssl, when I try to visit https://site1.domain.com:3443 it took long time and end up response time out error.</p>
<p>I use <strong>netstat</strong> to ensure the 3443 port is listening.</p>
```root@VM-4-10-ubuntu:~# netstat -anp | grep 443
tcp6       0      0 :::3443                 :::*                    LISTEN      164500/java
tcp6       0      0 :::443                  :::*                    LISTEN      164500/java
```

both domains can reach my server, I have test by keep only one sslConnector config and have the port set to 443.

so does Ktor support this?

of source I can use reverse proxy such as Nginx to do this, just seeking whether Ktor can do this or not

Body:
I want to use Ktor to serve two domains, with individual ssl certificate, below is my configuration to do :

val environment = applicationEngineEnvironment {
    val pwdCharArray = "password1".toCharArray()
    val kstFile = File("perkey/site1.jks")
    val keyStore = KeyStore.getInstance("JKS").apply { load(kstFile.inputStream(), pwdCharArray) }
    sslConnector(
        keyStore = keyStore,
        keyAlias = "site1",
        keyStorePassword = { pwdCharArray },
        privateKeyPassword = { pwdCharArray }
    ) {
        host = "site1.domain.com"
        port = 3443
        keyStorePath = kstFile
    }

    val pwdCharArray2 = "site2".toCharArray()
    val kstFile2 = File("perkey/site2.jks")
    val keyStore2 = KeyStore.getInstance("JKS").apply { load(kstFile2.inputStream(), pwdCharArray2) }
    sslConnector(
        keyStore = keyStore2,
        keyAlias = "site2",
        keyStorePassword = { pwdCharArray2 },
        privateKeyPassword = { pwdCharArray2 }
    ) {
        host = "site2.domain.com"
        port = 443
        keyStorePath = kstFile2
    }

    module(Application::module)
}
embeddedServer(Tomcat, environment).start(wait = true)

after ./gradlew run I saw the log:

2022-12-19 22:46:28 INFO Responding at https://site1.domain.com:3443
2022-12-19 22:46:28 INFO Responding at https://site2.domain.com:443

but I can only visit the site2.domain.com that used the default port of ssl, when I try to visit https://site1.domain.com:3443 it took long time and end up response time out error.

I use netstat to ensure the 3443 port is listening.

root@VM-4-10-ubuntu:~# netstat -anp | grep 443
tcp6       0      0 :::3443                 :::*                    LISTEN      164500/java
tcp6       0      0 :::443                  :::*                    LISTEN      164500/java

both domains can reach my server, I have test by keep only one sslConnector config and have the port set to 443.

so does Ktor support this?

of source I can use reverse proxy such as Nginx to do this, just seeking whether Ktor can do this or not


问:
Dalaran Flying enabled
Is there any way to configure Dalaran as a flying zone?
I have managed to remove the debuff by commenting out case 58600: from spellmgr.cpp among other things but all this do is remove the dismount debuff when already on a flying mount.

Any tips on how to allow flying mounts to be used in Dalaran?

Title: Dalaran Flying enabled


问:
It is any possibility to use Actuator's /info or gorylenko.git.propeties in Quarkus?
SpringBoot has functionality to provide deployed artifact version/commit intomation using Spring Actuator's /info or gorylenko.git.propeties.

Did we have any simillar functionality in Quarkus frm (https://quarkus.io/) ?

provide Git information on runtime for test envoirement


问:
Use "npm install -name-" removes "npm link" dirs from node_modules
I have my development package. I did "npm link" for it.
Now I go to another project and set up it here "npm link my".
Everything is good at this stage.

npm install node-fetch
But if I need to install something else, then after installation, my first project (link to my) disappears from node_modules.

And I have to do the installation again.
npm link my

Why is this happening? It is very uncomfortable.

npm 8.11.0 / Win10

This has happened many times and needs to be reinstalled each time.


问:
Minimal svelte + vitejs configuration for pre-rendered single-page app?
I have a very basic setup for Svelte with ViteJS for a single-page app that requires no routing and has all dependencies inlined by the vite-plugin-singlefile plugin.

The one thing that I cannot get to work is pre-rendered markup.

I would like to have the single-page app pre-rendered at build time, with the initial markup inlined in index.html for SEO, and hydration on the client side.

The vite-ssr-plugin seems to be targeting this scenario but incompatible with vite-plugin-singlefile. It generates a whole bunch of client / server files when used alone.

sveltekit on the other hand seems to be targeting more advanced scenarios and also generates a myriad of output files.

Is there any simpler solution?


问:
How to rename a collection with MongoDB Rust Driver in a idiomatic way?
I'm currently able to rename collection using run_command and following the instructions on MongoDB reference.

Here is a snippet using run_command from the MongoDB Rust Driver:

```<code>let client_options = ClientOptions::parse("mongodb://localhost/").expect("Unable to parse uri");
let client = Client::with_options(client_options).expect("Unable to connect client");
let db = client.database("admin");
let cmd = doc!{"renameCollection": "test.order", "to": "test.orders2023"};

let result = db.run_command(cmd, None).await;
    match result {
        Ok(_) => println!("Collection renamed"),
        Err(e) => panic!("Unable to rename collection due to {}", e),
    }
</code>```

One of my concerns is that I wouldn't like to use the admin database. Avoid something like:

db.adminCommand( { renameCollection: "test.orders", to: "test.orders2014" } )

And use something more similar to within Rust:

```<code>db.orders.renameCollection( "orders2014" )
</code>```

Is there a more idiomatic way to do it? Or is there a method analog to the db.collection.renameCollection from MongoDB?

Body:
I'm currently able to rename collection using run_command and following the instructions on MongoDB reference.

Here is a snippet using run_command from the MongoDB Rust Driver:

let client_options = ClientOptions::parse("mongodb://localhost/").expect("Unable to parse uri");
let client = Client::with_options(client_options).expect("Unable to connect client");
let db = client.database("admin");
let cmd = doc!{"renameCollection": "test.order", "to": "test.orders2023"};

let result = db.run_command(cmd, None).await;
    match result {
        Ok(_) => println!("Collection renamed"),
        Err(e) => panic!("Unable to rename collection due to {}", e),
    }

One of my concerns is that I wouldn't like to use the admin database. Avoid something like:

db.adminCommand( { renameCollection: "test.orders", to: "test.orders2014" } )

And use something more similar to within Rust:

db.orders.renameCollection( "orders2014" )

Is there a more idiomatic way to do it? Or is there a method analog to the db.collection.renameCollection from MongoDB?


问:
Pictures in pyqt5 gridlayout look stretched when window is maximized
The window shows a set of pictures. Once the window is maximized the app shows all pics in the window so it resizes every image looking ugly. I'd like to prevent the streching and keep the aspect ratio. Any clue?

This is the code of the proof of concept:

```<code>QApplication, QListWidget, QAbstractItemView, QPushButton, QWidget,
QTabWidget, QVBoxLayout, QHBoxLayout, QLabel, QPlainTextEdit,
QTextEdit, QCheckBox, QFileDialog, QMessageBox, QGridLayout from
PyQt5.QtCore import QProcess, QTimer, Qt from PyQt5.QtGui import QFont, QPixmap import os from QLabelClickable import QLabelClickable

class ExampleApp(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Example'
        self.left = 0
        self.top = 0
        self.width = 1000
        self.height = 800
        self.setMaximumWidth(1000)
        self.setMaximumHeight(800)
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

        data = []

        for root, dirs, files in os.walk('img/'):
            for file in files:
                filepath = os.path.join(root, file)
                data.append(filepath)

        self.picture_window = PictureWindow(data=data)
        self.picture_window.show()

class PictureWindow(QWidget):
    def __init__(self, data):
        super().__init__()
        self.n_columns = 5
        self.data = data

        self.gridLayout = QGridLayout()
        for i, filename in enumerate(self.data):
            self.render_picture(filename=filename, pos=i)

        self.setLayout(self.gridLayout)

    def render_picture(self, filename, pos):
        image_widget = QLabelClickable(pos)
        image_widget.setGeometry(15, 15, 118, 130)
        image_widget.setToolTip(filename)
        image_widget.setCursor(Qt.PointingHandCursor)

        self.pixmapImagen = QPixmap(filename).scaled(375, 375, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        image_widget.setPixmap(self.pixmapImagen)
        image_widget.setAlignment(Qt.AlignCenter)

        cell_layout = QVBoxLayout()
        cell_layout.setAlignment(Qt.AlignHCenter)
        cell_layout.addWidget(image_widget)
        self.gridLayout.addLayout(cell_layout, int(pos / self.n_columns), pos % self.n_columns)

from PyQt5.QtCore import Qt, pyqtSignal, QTimer
from PyQt5.QtWidgets import QApplication, QDialog, QLabel, QMessageBox

class QLabelClickable(QLabel):
    clicked = pyqtSignal(str)

    def __init__(self, id, parent=None):
        super(QLabelClickable, self).__init__(parent)
        self.id = id

    def mousePressEvent(self, event):
        self.ultimo = "Click"

    def mouseReleaseEvent(self, event):
        if self.ultimo == "Click":
            QTimer.singleShot(QApplication.instance().doubleClickInterval(),
                              self.performSingleClickAction)
        else:
            self.clicked.emit(self.ultimo+"-"+str(self.id))

    def mouseDoubleClickEvent(self, event):
        self.ultimo = "Double Click"

    def performSingleClickAction(self):
        if self.ultimo == "Click":
            self.clicked.emit(self.ultimo+"-"+str(self.id))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ExampleApp()
    sys.exit(app.exec_())
</code>```

This is how it looks when window is normal:

And looks like this when window is maximized:

After a few days trying to figure out what's going on here I an't go further, could you please help me to spot anything wrong?

I expect the pics to keepe their aspect ratio to implement a ScrollArea later on.

Body:
The window shows a set of pictures. Once the window is maximized the app shows all pics in the window so it resizes every image looking ugly. I'd like to prevent the streching and keep the aspect ratio. Any clue?

This is the code of the proof of concept:

QApplication, QListWidget, QAbstractItemView, QPushButton, QWidget,
QTabWidget, QVBoxLayout, QHBoxLayout, QLabel, QPlainTextEdit,
QTextEdit, QCheckBox, QFileDialog, QMessageBox, QGridLayout from
PyQt5.QtCore import QProcess, QTimer, Qt from PyQt5.QtGui import QFont, QPixmap import os from QLabelClickable import QLabelClickable

class ExampleApp(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Example'
        self.left = 0
        self.top = 0
        self.width = 1000
        self.height = 800
        self.setMaximumWidth(1000)
        self.setMaximumHeight(800)
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

        data = []

        for root, dirs, files in os.walk('img/'):
            for file in files:
                filepath = os.path.join(root, file)
                data.append(filepath)

        self.picture_window = PictureWindow(data=data)
        self.picture_window.show()

class PictureWindow(QWidget):
    def __init__(self, data):
        super().__init__()
        self.n_columns = 5
        self.data = data

        self.gridLayout = QGridLayout()
        for i, filename in enumerate(self.data):
            self.render_picture(filename=filename, pos=i)

        self.setLayout(self.gridLayout)

    def render_picture(self, filename, pos):
        image_widget = QLabelClickable(pos)
        image_widget.setGeometry(15, 15, 118, 130)
        image_widget.setToolTip(filename)
        image_widget.setCursor(Qt.PointingHandCursor)

        self.pixmapImagen = QPixmap(filename).scaled(375, 375, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        image_widget.setPixmap(self.pixmapImagen)
        image_widget.setAlignment(Qt.AlignCenter)

        cell_layout = QVBoxLayout()
        cell_layout.setAlignment(Qt.AlignHCenter)
        cell_layout.addWidget(image_widget)
        self.gridLayout.addLayout(cell_layout, int(pos / self.n_columns), pos % self.n_columns)

from PyQt5.QtCore import Qt, pyqtSignal, QTimer
from PyQt5.QtWidgets import QApplication, QDialog, QLabel, QMessageBox

class QLabelClickable(QLabel):
    clicked = pyqtSignal(str)

    def __init__(self, id, parent=None):
        super(QLabelClickable, self).__init__(parent)
        self.id = id

    def mousePressEvent(self, event):
        self.ultimo = "Click"

    def mouseReleaseEvent(self, event):
        if self.ultimo == "Click":
            QTimer.singleShot(QApplication.instance().doubleClickInterval(),
                              self.performSingleClickAction)
        else:
            self.clicked.emit(self.ultimo+"-"+str(self.id))

    def mouseDoubleClickEvent(self, event):
        self.ultimo = "Double Click"

    def performSingleClickAction(self):
        if self.ultimo == "Click":
            self.clicked.emit(self.ultimo+"-"+str(self.id))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ExampleApp()
    sys.exit(app.exec_())

This is how it looks when window is normal:

And looks like this when window is maximized:

After a few days trying to figure out what's going on here I an't go further, could you please help me to spot anything wrong?

I expect the pics to keepe their aspect ratio to implement a ScrollArea later on.


问:
React sortable hoc drop my items to the end of the list
When I using react sortable hoc library and dragging an item, it changes the transform3d of each li item (who is under the dragging item) to -22px what cause the item I dropped to be sent to the end of the list.

How can I change it to make transform only the relevant items?

An example

source code

I try to look for it on the internet and didn't find solution


问:
Fire button event after select multiple values in mat-select multiple
I have one mat-select with multiple select.

Right now, after choose several values from dropdown, I clicked the Submit button but it close dropdown first, not fire an event.

I need to click one more time and button will fire event.

How I just click one time in the Submit button and fire event with selected values from dropdown?

Any help will be appriciated.


问:
Insert on try to update
I have oneToOne relation. User and Profile
From the user side, I declare JoinColumn

I want to change take Profile to Another User
I am trying to save the new user in this way:

```<code>  const existingProfile =
      await this.profileService.getProfile(
        id
      );

    const user = await this.UserRepository.save({
      profile: existingProfile,
    });
</code>```

but Typeorm is trying to save a new profile and generates an error

the duplicate key value violates the unique constraint
Key ("profileId")=(6) already exists.

For some reason I can't previously delete that value or create a new profile with the same parameters
Maybe I do something wrong or had some workaround?

Title: Insert on try to update

Body:
I have oneToOne relation. User and Profile
From the user side, I declare JoinColumn

I want to change take Profile to Another User
I am trying to save the new user in this way:

  const existingProfile =
      await this.profileService.getProfile(
        id
      );

    const user = await this.UserRepository.save({
      profile: existingProfile,
    });

but Typeorm is trying to save a new profile and generates an error

the duplicate key value violates the unique constraint
Key ("profileId")=(6) already exists.

For some reason I can't previously delete that value or create a new profile with the same parameters
Maybe I do something wrong or had some workaround?


问:
how to call a click function inside loop with elements created dynamically using angular 9?
I made a kebab-style menu, inside a list, and btn (called add new account) to add new elements to the table, when I click on btn to add new elements, the kebabMenu() function is not opening the menu as it should , the function is executed only the first time.

calling the method

  ngAfterViewInit(): void {
    this.kebabMenu();
  }
```
<p>function to display menu:</p>
<pre class="lang-js prettyprint-override"><code>private kebabMenu(): void {
  let triggers: NodeList = this.elem.nativeElement.querySelectorAll('.trigger');
  let dropdowns: NodeList = this.elem.nativeElement.querySelectorAll('.dropdown');
  let crosses: NodeList = this.elem.nativeElement.querySelectorAll('.cross');
  let kebabs: NodeList = this.elem.nativeElement.querySelectorAll('.kebab');

  const clicks$ = fromEvent<MouseEvent>(triggers, 'click');

  clicks$.subscribe((e: MouseEvent) => {
    e.preventDefault();

    const index = Array.from(triggers as unknown as HTMLCollection).indexOf(e.currentTarget as HTMLElement)

    let cross = crosses[index] as HTMLElement;
    let drop = dropdowns[index] as HTMLElement;
    let kebab = kebabs[index] as HTMLElement;

    cross.classList.toggle('active');
    drop.classList.toggle('active');
    kebab.classList.toggle('bg-none');
  });
}
</code>```

Link do stackblitz = DEMO

project screen:

Body:
I made a kebab-style menu, inside a list, and btn (called add new account) to add new elements to the table, when I click on btn to add new elements, the kebabMenu() function is not opening the menu as it should , the function is executed only the first time.

calling the method

  ngAfterViewInit(): void {
    this.kebabMenu();
  }

function to display menu:

private kebabMenu(): void {
  let triggers: NodeList = this.elem.nativeElement.querySelectorAll('.trigger');
  let dropdowns: NodeList = this.elem.nativeElement.querySelectorAll('.dropdown');
  let crosses: NodeList = this.elem.nativeElement.querySelectorAll('.cross');
  let kebabs: NodeList = this.elem.nativeElement.querySelectorAll('.kebab');

  const clicks$ = fromEvent<MouseEvent>(triggers, 'click');

  clicks$.subscribe((e: MouseEvent) => {
    e.preventDefault();

    const index = Array.from(triggers as unknown as HTMLCollection).indexOf(e.currentTarget as HTMLElement)

    let cross = crosses[index] as HTMLElement;
    let drop = dropdowns[index] as HTMLElement;
    let kebab = kebabs[index] as HTMLElement;

    cross.classList.toggle('active');
    drop.classList.toggle('active');
    kebab.classList.toggle('bg-none');
  });
}

Link do stackblitz = DEMO

project screen:


问:
ERROR:kafka.conn:DNS lookup failed for <container:id>:9092
I'm trying to send a message from python producer (not in docker) to a kafka broker in docker. I tried different solutions but I still end up with this error "ERROR:kafka.conn:DNS lookup failed for container:id:9092":

Ports are correct

Docker Ports are exposed

Advertised Listeners are configured

For kafka I followed this tutorial https://www.youtube.com/watch?v=ncTosfaZ5cQ with this repo https://github.com/marcel-dempers/docker-development-youtube-series/tree/master/messaging/kafka

Any ideas what I'm doing wrong? I find a few question that are the same as mine but I already integrated those solutions. Every advice is appreciated

this is my docker compose file

```<code>version: "3.8"
services:
  zookeeper-1:
    container_name: zookeeper-1
    image: aimvector/zookeeper:2.7.0
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - "2181:2181"
    build:
      context: ./zookeeper
    volumes:
      - ./config/zookeeper-1/zookeeper.properties:/kafka/config/zookeeper.properties
      - ./data/zookeeper-1/:/tmp/zookeeper/data

  broker-2:
    container_name: broker-2
    image: aimvector/kafka:2.7.0
    build:
      context: .
    ports:
      - "9092:9092"
      - "29092:29092"
    volumes:
      - ./config/broker-2/server.properties:/kafka/config/server.properties
      - ./data/broker-2/:/tmp/kafka-logs/
    restart: always
    environment:
      ALLOW_PLAINTEXT_LISTENER: yes
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://broker-2:29092, EXTERNAL://127.0.0.1:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT, EXTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL

</code>```

And this is my python file:

```<code>producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092'])

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    print("Connected?", producer.bootstrap_connected())
    topic = "Kafka"
    producer.send(topic, b'testMessage')
    producer.flush()
    producer.close()

</code>```

this is my server.properties file

```<code># The id of the broker. This must be set to a unique integer for each broker.
broker.id=0

# The number of threads that the server uses for receiving requests from the network and sending responses to the network
num.network.threads=3

# The number of threads that the server uses for processing requests, which may include disk I/O
num.io.threads=8

# The send buffer (SO_SNDBUF) used by the socket server
socket.send.buffer.bytes=102400

# The receive buffer (SO_RCVBUF) used by the socket server
socket.receive.buffer.bytes=102400

# The maximum size of a request that the socket server will accept (protection against OOM)
socket.request.max.bytes=104857600

############################# Log Basics #############################

# A comma separated list of directories under which to store log files
log.dirs=/tmp/kafka-logs

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=1

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1

############################# Log Retention Policy #############################

# The minimum age of a log file to be eligible for deletion due to age
log.retention.hours=1

# The maximum size of a log segment file. When this size is reached a new log segment will be created.
log.segment.bytes=1073741824

# The interval at which log segments are checked to see if they can be deleted according
# to the retention policies
log.retention.check.interval.ms=300000

############################# Zookeeper #############################

# Zookeeper connection string (see zookeeper docs for details).
# This is a comma separated host:port pairs, each corresponding to a zk
# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
# You can also append an optional chroot string to the urls to specify the
# root directory for all kafka znodes.
zookeeper.connect=zookeeper-1:2181

# Timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=18000

############################# Group Coordinator Settings #############################

# The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
# The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
# The default value for this is 3 seconds.
# We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
# However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
group.initial.rebalance.delay.ms=0

</code>```

kafka is running fine on docker

Body:
I'm trying to send a message from python producer (not in docker) to a kafka broker in docker. I tried different solutions but I still end up with this error "ERROR:kafka.conn:DNS lookup failed for container:id:9092":

Ports are correct

Docker Ports are exposed

Advertised Listeners are configured

For kafka I followed this tutorial https://www.youtube.com/watch?v=ncTosfaZ5cQ with this repo https://github.com/marcel-dempers/docker-development-youtube-series/tree/master/messaging/kafka

Any ideas what I'm doing wrong? I find a few question that are the same as mine but I already integrated those solutions. Every advice is appreciated

this is my docker compose file

version: "3.8"
services:
  zookeeper-1:
    container_name: zookeeper-1
    image: aimvector/zookeeper:2.7.0
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - "2181:2181"
    build:
      context: ./zookeeper
    volumes:
      - ./config/zookeeper-1/zookeeper.properties:/kafka/config/zookeeper.properties
      - ./data/zookeeper-1/:/tmp/zookeeper/data

  broker-2:
    container_name: broker-2
    image: aimvector/kafka:2.7.0
    build:
      context: .
    ports:
      - "9092:9092"
      - "29092:29092"
    volumes:
      - ./config/broker-2/server.properties:/kafka/config/server.properties
      - ./data/broker-2/:/tmp/kafka-logs/
    restart: always
    environment:
      ALLOW_PLAINTEXT_LISTENER: yes
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://broker-2:29092, EXTERNAL://127.0.0.1:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT, EXTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL

And this is my python file:

producer = KafkaProducer(bootstrap_servers=['127.0.0.1:9092'])

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    print("Connected?", producer.bootstrap_connected())
    topic = "Kafka"
    producer.send(topic, b'testMessage')
    producer.flush()
    producer.close()

this is my server.properties file

# The id of the broker. This must be set to a unique integer for each broker.
broker.id=0

# The number of threads that the server uses for receiving requests from the network and sending responses to the network
num.network.threads=3

# The number of threads that the server uses for processing requests, which may include disk I/O
num.io.threads=8

# The send buffer (SO_SNDBUF) used by the socket server
socket.send.buffer.bytes=102400

# The receive buffer (SO_RCVBUF) used by the socket server
socket.receive.buffer.bytes=102400

# The maximum size of a request that the socket server will accept (protection against OOM)
socket.request.max.bytes=104857600

############################# Log Basics #############################

# A comma separated list of directories under which to store log files
log.dirs=/tmp/kafka-logs

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=1

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1

############################# Log Retention Policy #############################

# The minimum age of a log file to be eligible for deletion due to age
log.retention.hours=1

# The maximum size of a log segment file. When this size is reached a new log segment will be created.
log.segment.bytes=1073741824

# The interval at which log segments are checked to see if they can be deleted according
# to the retention policies
log.retention.check.interval.ms=300000

############################# Zookeeper #############################

# Zookeeper connection string (see zookeeper docs for details).
# This is a comma separated host:port pairs, each corresponding to a zk
# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
# You can also append an optional chroot string to the urls to specify the
# root directory for all kafka znodes.
zookeeper.connect=zookeeper-1:2181

# Timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=18000

############################# Group Coordinator Settings #############################

# The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
# The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
# The default value for this is 3 seconds.
# We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
# However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
group.initial.rebalance.delay.ms=0

kafka is running fine on docker


问:
How to receive data from a Tcp/Ip connection in a webots controller?
I'm doing a project in the WEBOTS simulator and right now I'm implementing a TCP/IP communication to be able to pass information between controllers. In particular I have two controllers, one of them is the server and the other is the client. My problem appears when I need to receive the data sent by the server in the client controller, because I have a function that receives the data inside the while loop and while this function does not receive data it stays there and this makes the simulation not progress . This is the problem, the function that receives information, for the purpose of the project I need the controller to be always ready to receive information.

I leave here a print of the code of my client controller, as the information reception function is inside the while loop, while the function does not receive information, the simulation remains stopped.Print of the code in client controller


问:
Nginx proxy_pass - not able to reverse proxy with location other than /
I have following in my nginx.conf file in windows 10.

```<code>
#user  nobody;
worker_processes  1;

error_log  "C:\\nginx\\nginx-1.23.1\\logs\\error.log";

events {
    worker_connections  1024;
}

http {

    default_type  application/octet-stream;

    sendfile        on;
    tcp_nopush     on;
    tcp_nodelay on;
    keepalive_timeout  65;
    gzip  on;

    include       "C:\\nginx\\nginx-1.23.1\\conf\\mime.types";

    server {
        listen       8009;
        server_name  server;

        default_type application/octet-stream;

        location / {
            root   html;
            index  index.html index.htm;
        }

        location /myapp/ {
            proxy_pass http://172.17.122.45:8100/;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host $server_name;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Real-IP $remote_addr;
            #sub_filter_types *;
            sub_filter 'action="/'  'action="/myapp/';
            sub_filter 'href="/'  'href="/myapp/';
            sub_filter 'src="/'  'src="/myapp/';
            sub_filter_once off;
        }
    }
}

</code>```

I am trying to access app on http://server:8009/myapp/, but not able to access. Able to proxy_pass my app on location /, but not able to do it on any other location.
It's able to load the js files but not few json files and images. Showing console error in browser as below.

```<code>main.5e06c118abe3f1a0.js:1 ERROR Error: Uncaught (in promise): zx: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://server:8009/assets/envsettings.json","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://server:8009/assets/envsettings.json","error":{"error":{},"text":"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"/><base href=\"/\"/><meta content=\"width=device-width,initial-scale=1\" name=\"viewport\"/><meta content=\"#081C42\" media=\"(prefers-color-scheme: light)\" name=\"theme-color\"/><meta content=\"#081C42\" media=\"(prefers-color-scheme: dark)\" name=\"theme-color\"/><meta content=\"MinIO Console\" name=\"description\"/><link href=\"./styles/root-styles.css\" rel=\"stylesheet\"/><link href=\"./apple-icon-180x180.png\" rel=\"apple-touch-icon\" sizes=\"180x180\"/><link href=\"./favicon-32x32.png\" rel=\"icon\" sizes=\"32x32\" type=\"image/png\"/><link href=\"./favicon-96x96.png\" rel=\"icon\" sizes=\"96x96\" type=\"image/png\"/><link href=\"./favicon-16x16.png\" rel=\"icon\" sizes=\"16x16\" type=\"image/png\"/><link href=\"./manifest.json\" rel=\"manifest\"/><link color=\"#3a4e54\" href=\"./safari-pinned-tab.svg\" rel=\"mask-icon\"/><title>MinIO Console</title><script defer=\"defer\" src=\"./static/js/main.44b939e3.js\"></script><link href=\"./static/css/main.90d417ae.css\" rel=\"stylesheet\"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id=\"root\"><div id=\"preload\"><img src=\"./images/background.svg\"/> <img src=\"./images/background-wave-orig2.svg\"/></div><div id=\"loader-block\"><img src=\"./Loader.svg\"/></div></div></body></html>"}}
</code>```

It's trying to access http://server:8009/assets/envsettings.json instead of http://server:8009/myapp/assets/envsettings.json. What I'm doing wrong here? I'm pretty new to nginx.

Body:
I have following in my nginx.conf file in windows 10.

#user  nobody;
worker_processes  1;

error_log  "C:\\nginx\\nginx-1.23.1\\logs\\error.log";

events {
    worker_connections  1024;
}

http {

    default_type  application/octet-stream;

    sendfile        on;
    tcp_nopush     on;
    tcp_nodelay on;
    keepalive_timeout  65;
    gzip  on;

    include       "C:\\nginx\\nginx-1.23.1\\conf\\mime.types";

    server {
        listen       8009;
        server_name  server;

        default_type application/octet-stream;

        location / {
            root   html;
            index  index.html index.htm;
        }

        location /myapp/ {
            proxy_pass http://172.17.122.45:8100/;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host $server_name;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Real-IP $remote_addr;
            #sub_filter_types *;
            sub_filter 'action="/'  'action="/myapp/';
            sub_filter 'href="/'  'href="/myapp/';
            sub_filter 'src="/'  'src="/myapp/';
            sub_filter_once off;
        }
    }
}

I am trying to access app on http://server:8009/myapp/, but not able to access. Able to proxy_pass my app on location /, but not able to do it on any other location.
It's able to load the js files but not few json files and images. Showing console error in browser as below.

main.5e06c118abe3f1a0.js:1 ERROR Error: Uncaught (in promise): zx: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://server:8009/assets/envsettings.json","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://server:8009/assets/envsettings.json","error":{"error":{},"text":"<!doctype html><meta charset=\"utf-8\"/><base href=\"/\"/><meta content=\"width=device-width,initial-scale=1\" name=\"viewport\"/><meta content=\"#081C42\" media=\"(prefers-color-scheme: light)\" name=\"theme-color\"/><meta content=\"#081C42\" media=\"(prefers-color-scheme: dark)\" name=\"theme-color\"/><meta content=\"MinIO Console\" name=\"description\"/><link href=\"./styles/root-styles.css\" rel=\"stylesheet\"/><link href=\"./apple-icon-180x180.png\" rel=\"apple-touch-icon\" sizes=\"180x180\"/><link href=\"./favicon-32x32.png\" rel=\"icon\" sizes=\"32x32\" type=\"image/png\"/><link href=\"./favicon-96x96.png\" rel=\"icon\" sizes=\"96x96\" type=\"image/png\"/><link href=\"./favicon-16x16.png\" rel=\"icon\" sizes=\"16x16\" type=\"image/png\"/><link href=\"./manifest.json\" rel=\"manifest\"/><link color=\"#3a4e54\" href=\"./safari-pinned-tab.svg\" rel=\"mask-icon\"/><title>MinIO Console</title><link href=\"./static/css/main.90d417ae.css\" rel=\"stylesheet\">You need to enable JavaScript to run this app.

"}}

It's trying to access http://server:8009/assets/envsettings.json instead of http://server:8009/myapp/assets/envsettings.json. What I'm doing wrong here? I'm pretty new to nginx.


问:
I want to use teams outgoing webhook to send comments on a post to salesforce. Is there a way to send comments from teams to salesforce
My scenario is, if someone posts a discussion in salesforce community, we are sending it to teams through incoming webhook. I would like to explore if we can reply in the post, can we send it back to salesforce

I tried teams integration for salesforce but it doesn't work for salesforce communities.


问:
How to access ID2D1HwndRenderTarget->Resize using C++ builder TDirect2DCanvas
I've been trying to use TDirect2D in my c++ builder project. I've been using the following code to gain access to Direct2D Canvas.

```<code>void __fastcall TCustomDrawPanel::Paint()
{

    if ( TDirect2DCanvas::Supported() )
    {
        std::unique_ptr<TDirect2DCanvas> D2DC(
            new TDirect2DCanvas( Canvas, ClientRect )
        );

        struct DrawSession {
            explicit DrawSession( TDirect2DCanvas& Canvas )
              : c_( Canvas ) { c_.BeginDraw(); }
            ~DrawSession() {
                try {
                    c_.EndDraw();
                }
                catch ( ... ) {
                }
            }
            TDirect2DCanvas& c_;
        }
        D2DSession( *D2DC );

           DDrawPanel(D2DC);
    }
</code>```

This code works fine, but the Direct2D resources have to be acquired and released on each repaint. So I'm using the example found On Embarcadero website. For that example to work properly I'll have to resize the render target when ever the window is resized. The example given on the website is in Delphi as shown below.

```<code>
procedure T2D2Form.WMSize(var Message: TWMSize);
 begin
   if Assigned(FCanvas) then
     ID2D1HwndRenderTarget(FCanvas.RenderTarget).Resize(D2D1SizeU(ClientWidth,
                                                                  ClientHeight));

   inherited;
 end;
</code>```

My question is how can I convert this to c++ builder code? I've tried many different ways to cast FCanvas->RenderTarget but the code won't compile.

I've tried the following:

```<code>ID2D1HwndRenderTarget * target =
    dynamic_cast < Winapi::D2d1::ID2D1HwndRenderTarget * > (FCanvas->RenderTarget);
</code>```

I can use target->Resize(D2D1SizeU(ClientWidth, ClientHeight)) to change render size if I can get the code to compile.

Body:
I've been trying to use TDirect2D in my c++ builder project. I've been using the following code to gain access to Direct2D Canvas.

void __fastcall TCustomDrawPanel::Paint()
{

    if ( TDirect2DCanvas::Supported() )
    {
        std::unique_ptr<TDirect2DCanvas> D2DC(
            new TDirect2DCanvas( Canvas, ClientRect )
        );

        struct DrawSession {
            explicit DrawSession( TDirect2DCanvas& Canvas )
              : c_( Canvas ) { c_.BeginDraw(); }
            ~DrawSession() {
                try {
                    c_.EndDraw();
                }
                catch ( ... ) {
                }
            }
            TDirect2DCanvas& c_;
        }
        D2DSession( *D2DC );

           DDrawPanel(D2DC);
    }

This code works fine, but the Direct2D resources have to be acquired and released on each repaint. So I'm using the example found On Embarcadero website. For that example to work properly I'll have to resize the render target when ever the window is resized. The example given on the website is in Delphi as shown below.

procedure T2D2Form.WMSize(var Message: TWMSize);
 begin
   if Assigned(FCanvas) then
     ID2D1HwndRenderTarget(FCanvas.RenderTarget).Resize(D2D1SizeU(ClientWidth,
                                                                  ClientHeight));

   inherited;
 end;

My question is how can I convert this to c++ builder code? I've tried many different ways to cast FCanvas->RenderTarget but the code won't compile.

I've tried the following:

ID2D1HwndRenderTarget * target =
    dynamic_cast < Winapi::D2d1::ID2D1HwndRenderTarget * > (FCanvas->RenderTarget);

I can use target->Resize(D2D1SizeU(ClientWidth, ClientHeight)) to change render size if I can get the code to compile.


问:
How to show front camera like in the whatsapp video call in the corner of the screen?
Hello Developers I want to show front camera at the corner of the screen on my app.
In this way

Demo

I have tried these methods
How do I open the "front camera" on the Android platform?
Front face camera android.
How to launch front camera with intent?

but these methods overrides completes screen and I just want to show front camera at the top corner so that any user can see him/herself.

I have tried to open front camera using Intent but it overrides complete screen and I am expecting to show front camera at the top corner of the app


问:
RuntimeError: Cannot find GRASS GIS start script: C:/Program Files/GRASS GIS 7.8, set the right one using the GRASSBIN environm. variable
I try to use GRASSGIS via Python3. But when I import grass_session, Python gives out an error message: "RuntimeError: Cannot find GRASS GIS start script: C:/Program Files/GRASS GIS 7.8, set the right one using the GRASSBIN environm. variable"

Here's my code:

```<code>import os
import sys
import subprocess

grass7bin = r'C:/Program Files/GRASS GIS 7.8/grass78.bat'
startcmd = [grass7bin, '--config', 'path']
try:
    p = subprocess.Popen(startcmd, shell=False,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
except OSError as error:
    sys.exit("ERROR: Cannot find GRASS GIS start script"
             " {cmd}: {error}".format(cmd=startcmd[0], error=error))
if p.returncode != 0:
    sys.exit("ERROR: Issues running GRASS GIS start script"
             " {cmd}: {error}"
             .format(cmd=' '.join(startcmd), error=err))
gisbase = r'C:/Program Files/GRASS GIS 7.8'

os.environ['GISBASE'] = gisbase
grass_pydir = os.path.join(gisbase, "etc", "python")
sys.path.append(grass_pydir)

import grass.script.setup as gsetup

gisdb = os.path.join(os.path.expanduser("~"), "C:/Users/user/Documents/grassdata")
location = "Testlocation"
mapset = "test"

rcfile = gsetup.init(gisbase, gisdb, location, mapset)

# use grass functions here

os.remove(rcfile)

import grass_session as session
</code>```

What do I wrong?

Body:
I try to use GRASSGIS via Python3. But when I import grass_session, Python gives out an error message: "RuntimeError: Cannot find GRASS GIS start script: C:/Program Files/GRASS GIS 7.8, set the right one using the GRASSBIN environm. variable"

Here's my code:

import os
import sys
import subprocess

grass7bin = r'C:/Program Files/GRASS GIS 7.8/grass78.bat'
startcmd = [grass7bin, '--config', 'path']
try:
    p = subprocess.Popen(startcmd, shell=False,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
except OSError as error:
    sys.exit("ERROR: Cannot find GRASS GIS start script"
             " {cmd}: {error}".format(cmd=startcmd[0], error=error))
if p.returncode != 0:
    sys.exit("ERROR: Issues running GRASS GIS start script"
             " {cmd}: {error}"
             .format(cmd=' '.join(startcmd), error=err))
gisbase = r'C:/Program Files/GRASS GIS 7.8'

os.environ['GISBASE'] = gisbase
grass_pydir = os.path.join(gisbase, "etc", "python")
sys.path.append(grass_pydir)

import grass.script.setup as gsetup

gisdb = os.path.join(os.path.expanduser("~"), "C:/Users/user/Documents/grassdata")
location = "Testlocation"
mapset = "test"

rcfile = gsetup.init(gisbase, gisdb, location, mapset)

# use grass functions here

os.remove(rcfile)

import grass_session as session

What do I wrong?


问:
Webclient serializing booleans with initial underscore
```<code>public MyClass {
    private String field1;
    private String field2;
    private boolean field3;

    public MyClass() {
        this.field1 = "value1";
        this.field2 = "value2";
        this.field3 = false;
    }

    getters/setters...
}
</code>```

When passing it to Webclient as the body of a post, the JSON that gets generated is:

```<code>{
    "field1": "value1",
    "field2": "value2",
    "_field3": on
}
</code>```

with field3's name changed and having a value that is always 'on'.

I haven't found a way to disable this: is it possible? Am I doing something wrong?

I tried adding @JsonProperty to the field and @JsonObject to the class but nothing changed. I'd expect the Json to be:

```<code>{
    "field1": "value1",
    "field2": "value2",
    "field3": false
}
</code>```

which is what the webservice is expecting.

Body:
public MyClass {
    private String field1;
    private String field2;
    private boolean field3;

    public MyClass() {
        this.field1 = "value1";
        this.field2 = "value2";
        this.field3 = false;
    }

    getters/setters...
}

When passing it to Webclient as the body of a post, the JSON that gets generated is:

{
    "field1": "value1",
    "field2": "value2",
    "_field3": on
}

with field3's name changed and having a value that is always 'on'.

I haven't found a way to disable this: is it possible? Am I doing something wrong?

I tried adding @JsonProperty to the field and @JsonObject to the class but nothing changed. I'd expect the Json to be:

{
    "field1": "value1",
    "field2": "value2",
    "field3": false
}

which is what the webservice is expecting.


问:
Daphne processes run by supervisor don't share memory
I have a Django app that uses Daphne behind Nginx as an app server.
I have first used Gunicorn + Uvicorn as an app server but I ran into a problem that I thought I could avoid by simply switching to Daphne. Unfortunately, when I switched to Daphne, the same problem remained.

Description of the problem:
I have an app that has users. I save active users in an array. It's all good while I have only one Gunicorn+Uvicorn worker or one Daphne+Supervisor process. Problem starts when I introduce multiple workers/processes. I didn't know that each worker/process has its own memory, so when I log in I am logged in on only one of the workers. For example, let's say that I have 4 workers. I log in. First response in app is okay but all the other are random and the more workers I have, the less chance there is that I'll get a right answer. That is, chances are equal to 1/n where n is a number of workers/processes. That's because logged in user is saved in an array on only one of those workers memory.

So, I need some tips how to solve that problem and make workers/processes share that array with logged in users.
I saw that there is a --preload flag in Gunicorn but it makes copy on write for workers, so if I understand it correctly, when I log in on the current worker, main process memory will copy itself only for that specific worker and I'll still be logged in only one instance of the app.

What I need is an array to which all processes have an access.

I am at the moment trying to make it work using multiprocessing module, but if someone has a nicer solution, I'd really appreciate it.

All advices are welcome! Thank you! :D


问:
using foreign keys with MudDataGrid
I have the following object:
`

```<code>    public class Permissions : Item
    {
        public int Id { get; set; }
        public AppUser User { get; set; }
        public Component Component { get; set; }
        public string Permission { get; set; }

    }
</code>```

`

My MudDataGrid:
`

```<code><MudDataGrid T="Permissions" Items="@permissions" ReadOnly="@_readOnly" EditMode="@(_isCellEditMode ? DataGridEditMode.Cell : DataGridEditMode.Form)"
             StartedEditingItem="@StartedEditingItem" CancelledEditingItem="@CancelledEditingItem" CommittedItemChanges="@CommittedItemChanges"
             Bordered="true" Dense="true" EditTrigger="@(_editTriggerRowClick ? DataGridEditTrigger.OnRowClick : DataGridEditTrigger.Manual)">
    <Columns>
        <Column T="Permissions" Field="User" Title="UserName" IsEditable="false" />
        <Column T="Permissions" Field="**Component.ComponentName**" IsEditable="false" />
        <Column T="Permissions" Field="Permission" />
        <Column T="Permissions" Hidden="@(_isCellEditMode || _readOnly || _editTriggerRowClick)" CellClass="d-flex justify-end">
            <CellTemplate>
                <MudIconButton Size="@Size.Small" Icon="@Icons.Outlined.Edit" OnClick="@context.Actions.StartEditingItem" />
            </CellTemplate>
        </Column>
    </Columns>

</code>```

`

both 'AppUser' and 'Component' are foreign keys to other objects. Data is returned fine, however I am having dificulty displaying these objects on the experimental MudDataGrid.
I know that the MudDataGrid isn't 'live' currently, but I'm only using it on a test system at present. Is anyone aware of a way for me to reference the items of the foreign object in the grid? I thought it would be something like 'Field="Component.ComponentName', but I get a nullreferenceexception.

I've tried 'Field="Component.ComponentName"' ,'Field="Component[ComponentName]"' to no avail.

Title: using foreign keys with MudDataGrid

Body:
I have the following object:
`

    public class Permissions : Item
    {
        public int Id { get; set; }
        public AppUser User { get; set; }
        public Component Component { get; set; }
        public string Permission { get; set; }

    }

`

My MudDataGrid:
`

<MudDataGrid T="Permissions" Items="@permissions" ReadOnly="@_readOnly" EditMode="@(_isCellEditMode ? DataGridEditMode.Cell : DataGridEditMode.Form)"
             StartedEditingItem="@StartedEditingItem" CancelledEditingItem="@CancelledEditingItem" CommittedItemChanges="@CommittedItemChanges"
             Bordered="true" Dense="true" EditTrigger="@(_editTriggerRowClick ? DataGridEditTrigger.OnRowClick : DataGridEditTrigger.Manual)">
    <Columns>
        <Column T="Permissions" Field="User" Title="UserName" IsEditable="false" />
        <Column T="Permissions" Field="**Component.ComponentName**" IsEditable="false" />
        <Column T="Permissions" Field="Permission" />
        <Column T="Permissions" Hidden="@(_isCellEditMode || _readOnly || _editTriggerRowClick)" CellClass="d-flex justify-end">
            <CellTemplate>
                <MudIconButton Size="@Size.Small" Icon="@Icons.Outlined.Edit" OnClick="@context.Actions.StartEditingItem" />
            </CellTemplate>
        </Column>
    </Columns>

`

both 'AppUser' and 'Component' are foreign keys to other objects. Data is returned fine, however I am having dificulty displaying these objects on the experimental MudDataGrid.
I know that the MudDataGrid isn't 'live' currently, but I'm only using it on a test system at present. Is anyone aware of a way for me to reference the items of the foreign object in the grid? I thought it would be something like 'Field="Component.ComponentName', but I get a nullreferenceexception.

I've tried 'Field="Component.ComponentName"' ,'Field="Component[ComponentName]"' to no avail.


问:
Why translating next.js page not work as expected after getStaticProps invalidation?
Quick summary:

I'm trying to use i18n with Next.js and translate my category page.

I'm using the getStaticProps function in order to translate my page and fetch data from DB.

The expected result: Fetch data from db, if the data has changed after 10 seconds then revalidate and show the page with the initial translation.

The actual results: I'm fetching the page for the first time and the data is displayed and the translation is ok, I'm changing something from DB and waiting 10 seconds. The data is changed correctly but the translation is not working (I can see the translation keys instead of the actual words e.g 'share_btn' instead 'Share' text).

```<code>
export async function getStaticProps(context) {
  try {
    await connect(); // My DB connection
    const files = await File.find({ category: 'some category', approved: true });

    return {
      props: {
        files: JSON.parse(JSON.stringify(files)),
        error: false,
        ...(await serverSideTranslations(
          context.locale,
          ['category', 'home'],
          i18nConfig
        )),
      },
      revalidate: 10,
    };
  } catch (e) {
    return {
      props: {
        files: [],
        error: true,
        ...(await serverSideTranslations(
          context.locale,
          ['category', 'home'],
          i18nConfig
        )),
      },
      revalidate: 10,
    };
  }
}
</code>```

versions of related technologies:

```<code>"next": "12.2.3",
"next-i18next": "12.0.1",
"react": "18.2.0",
"react-dom": "18.2.0",
</code>```

I will provide more information if needed.
Thanks.

Body:
Quick summary:

I'm trying to use i18n with Next.js and translate my category page.

I'm using the getStaticProps function in order to translate my page and fetch data from DB.

The expected result: Fetch data from db, if the data has changed after 10 seconds then revalidate and show the page with the initial translation.

The actual results: I'm fetching the page for the first time and the data is displayed and the translation is ok, I'm changing something from DB and waiting 10 seconds. The data is changed correctly but the translation is not working (I can see the translation keys instead of the actual words e.g 'share_btn' instead 'Share' text).

export async function getStaticProps(context) {
  try {
    await connect(); // My DB connection
    const files = await File.find({ category: 'some category', approved: true });

    return {
      props: {
        files: JSON.parse(JSON.stringify(files)),
        error: false,
        ...(await serverSideTranslations(
          context.locale,
          ['category', 'home'],
          i18nConfig
        )),
      },
      revalidate: 10,
    };
  } catch (e) {
    return {
      props: {
        files: [],
        error: true,
        ...(await serverSideTranslations(
          context.locale,
          ['category', 'home'],
          i18nConfig
        )),
      },
      revalidate: 10,
    };
  }
}

versions of related technologies:

"next": "12.2.3",
"next-i18next": "12.0.1",
"react": "18.2.0",
"react-dom": "18.2.0",

I will provide more information if needed.
Thanks.


问:
Consistency issue: build setting `IPHONEOS_DEPLOYMENT_TARGET` has multiple values
I generated new flutter module project for my existing app which has set iOS target to 15.0
I was following https://docs.flutter.dev/development/add-to-app/ios/project-setup this guide with option A but I'm getting this after pod install:

```<code>Analyzing dependencies
Downloading dependencies
Installing Flutter (1.0.0)
Installing FlutterPluginRegistrant (0.0.1)
Generating Pods project
[!] An error occurred while processing the post-install hook of the Podfile.

[Xcodeproj] Consistency issue: build setting `IPHONEOS_DEPLOYMENT_TARGET` has multiple values: `{"Release"=>"13.0", "Debug"=>"13.0", "Production"=>"15.0", "Store"=>"15.0"}`
</code>```

I tried changing the iOS version in pod file by setting target to 15.0 but its not working.
Changing anything in flutter .iOS dir is also not working

Body:
I generated new flutter module project for my existing app which has set iOS target to 15.0
I was following https://docs.flutter.dev/development/add-to-app/ios/project-setup this guide with option A but I'm getting this after pod install:

Analyzing dependencies
Downloading dependencies
Installing Flutter (1.0.0)
Installing FlutterPluginRegistrant (0.0.1)
Generating Pods project
[!] An error occurred while processing the post-install hook of the Podfile.

[Xcodeproj] Consistency issue: build setting `IPHONEOS_DEPLOYMENT_TARGET` has multiple values: `{"Release"=>"13.0", "Debug"=>"13.0", "Production"=>"15.0", "Store"=>"15.0"}`

I tried changing the iOS version in pod file by setting target to 15.0 but its not working.
Changing anything in flutter .iOS dir is also not working


问:
No Module Error in Pycharm ONLY When Using A Notebook
I am trying to import a method from a module outside the current module.
While I can do this from a script without any issue, when I try it from inside a Jupyter notebook, it fails. How do you suggest I investigate the issue?

Example: Imagine these be my directories.

```<code>- module_1
--- __inte__.py
--- my_lib.py
- module_2
--- __inte__.py
--- script_which_calls_from_my_lib.py
--- notebook_which_calls_from_my_lib.ipynb
</code>```

And I import the same way in both files (.py and .ipynb):

```<code>from module_1.my_lib import method_x
</code>```

In the example above, script_which_calls_from_my_lib.py imports the methods without any issue, but notebook_which_calls_from_my_lib.ipynb returns the following error:

```<code>ModuleNotFoundError: No module named 'module_1'
</code>```

Note: This seems to be an issue only within this project (in PyCharm). That is, when I tried to reproduced a minimal working example in a new project, it worked without an issue.

Note: I have cleaned up this project as much as I could. I removed venv and created a new one with only Jupyter installed, I closed the project in PyCharm, etc.

Edit

It seems that PyCharm 22.3 might be the cause of this error:

https://youtrack.jetbrains.com/issue/DS-4251

https://youtrack.jetbrains.com/issue/PY-57823

Body:
I am trying to import a method from a module outside the current module.
While I can do this from a script without any issue, when I try it from inside a Jupyter notebook, it fails. How do you suggest I investigate the issue?

Example: Imagine these be my directories.

- module_1
--- __inte__.py
--- my_lib.py
- module_2
--- __inte__.py
--- script_which_calls_from_my_lib.py
--- notebook_which_calls_from_my_lib.ipynb

And I import the same way in both files (.py and .ipynb):

from module_1.my_lib import method_x

In the example above, script_which_calls_from_my_lib.py imports the methods without any issue, but notebook_which_calls_from_my_lib.ipynb returns the following error:

ModuleNotFoundError: No module named 'module_1'

Note: This seems to be an issue only within this project (in PyCharm). That is, when I tried to reproduced a minimal working example in a new project, it worked without an issue.

Note: I have cleaned up this project as much as I could. I removed venv and created a new one with only Jupyter installed, I closed the project in PyCharm, etc.

Edit

It seems that PyCharm 22.3 might be the cause of this error:

https://youtrack.jetbrains.com/issue/DS-4251

https://youtrack.jetbrains.com/issue/PY-57823